util/script

Utility functions for building inline scripts that load external scripts without blocking the page.

Methods

(inner) appendScript(selector, url, attrs, dynamicAttrsopt) → {string}

Build an inline script that adds an external script to an element, for example the client script of a comment system that reads its options from the attributes of its own <script> tag.

The external script is added every time the inline script runs. Unlike a <script> tag in the page, which PJAX runs again without its attributes and outside of its element, it keeps its attributes and stays in the element. It is added after the inline script has finished, so that PJAX, which runs the scripts of the new page right after switching to it, does not run it again.

Source:
Parameters:
Name Type Attributes Description
selector string CSS selector of the element to add the external script to.
url string URL of the external script.
attrs Object Attributes to set on the external script element.
dynamicAttrs Object <optional>
More attributes, whose values are JavaScript expressions evaluated by the inline script, for example to choose a theme in the browser.
Returns:
Type:
string
The inline JavaScript code.
Example
appendScript('#comments-thread', 'https://comments.example.com/client.js', { repo: 'user/repo' }, {
  theme: "window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'",
});

(inner) loadScripts(urls, code, attrsopt) → {string}

Build an inline script that loads external scripts asynchronously and in order, and then runs the given code.

A script that is already on the page is not added again. If it has finished loading, or it was not added by this function, the next one is loaded, or the code runs, right away. This lets the inline script be run again, for example by PJAX after switching pages, without loading the external scripts twice.

Source:
Parameters:
Name Type Attributes Description
urls string | Array.<string> URL(s) of the external scripts to load, in order.
code string JavaScript code to run after all external scripts are loaded.
attrs Object <optional>
Extra attributes to set on the external script elements.
Returns:
Type:
string
The inline JavaScript code.
Example
<script dangerouslySetInnerHTML={{ __html: loadScripts('/path/to/lib.js', 'lib.init();') }} />

(inner) toJs(value) → {string}

Convert a value to JavaScript code that can be put in an inline <script>.

Unlike JSON.stringify alone, it escapes <, so that a value containing </script>, such as a page title, cannot end the inline script, and the line separators U+2028 and U+2029, which older browsers do not allow in JavaScript strings.

Source:
Parameters:
Name Type Description
value any A value that can be converted to JSON.
Returns:
Type:
string
The JavaScript code.
Example
toJs('</script>'); // '"\\u003c/script>"'