'Custom script type in HTML document
I am implementing a 3rd party widget and was given the following script:
<script type="acme/widget">
{
"some": "value" | "siteId": "hotel" | "money" | "travel"
}
</script>
Notice the custom script type acme/widget?
Browser console is complaining because the JavaScript interpreter tries to parse the illegal contents.
Uncaught SyntaxError: Unexpected token | in JSON at position 30
at JSON.parse (<anonymous>)
at p (app.js:1)
How can I make this custom script load on my page without errors? Is there a way to register a custom script type?
Solution 1:[1]
HTML LS as of 2022-02-20 states:
The
typeattribute allows customization of the type of script represented:
- […]
- Setting the attribute to any other value [than a JS MIME type or
"module"] means that the script is a data block, which is not processed. None of thescriptattributes (excepttypeitself) have any effect on data blocks. Authors must use a valid MIME type string that is not a JavaScript MIME type essence match to denote data blocks.
Which means that a script element with a type that is neither "module" nor a JavaScript MIME type ought to be ignored by the browser entirely. The stack trace in the question clearly comes from attempting to invoke JSON.parse on the contents of the element from within a script named ‘app.js’, which of course fails, because the contents are not valid JSON.
The only way to register your own script type is to have a script that finds all data block elements in the DOM, and then uses MutationObserver to catch any that are added afterwards. An example of doing just that can be found in Fengari, a JavaScript implementation of Lua.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user3840170 |
