- Source:
Methods
(inner) appendScript(selector, url, attrs, dynamicAttrsopt) → {string}
<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
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}
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
Example
<script dangerouslySetInnerHTML={{ __html: loadScripts('/path/to/lib.js', 'lib.init();') }} />
(inner) toJs(value) → {string}
<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
Example
toJs('</script>'); // '"\\u003c/script>"'