Last active
January 30, 2024 08:44
-
-
Save ryanmorr/1c73a7745d359820080003db9e8b0698 to your computer and use it in GitHub Desktop.
Pass data from an HTML script tag to JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const JSON_RE = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/; | |
function parseData(data) { | |
if (data == null || data === 'null' || data === 'undefined' || data === '') { | |
return null; | |
} | |
if (data === 'true') { | |
return true; | |
} | |
if (data === 'false') { | |
return false; | |
} | |
if (data === +data + '') { | |
return +data; | |
} | |
if (JSON_RE.test(data)) { | |
try { | |
return JSON.parse(data); | |
} catch(e) {} | |
} | |
return data; | |
} | |
function getScriptData(script = document.currentScript) { | |
const data = {}; | |
for (let name in script.dataset) { | |
data[name] = parseData(script.dataset[name]); | |
} | |
return data; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script data-foo="Hello World", data-bar="true" data-baz="14.5" data-qux="{"foo":"bar"}"> | |
const data = getScriptData(); | |
data.foo; //=> "Hello World" | |
data.bar; //=> true | |
data.baz; //=> 14.5 | |
data.qux; //=> {foo: "bar"} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment