Skip to content

Instantly share code, notes, and snippets.

@atsea
Created August 1, 2017 17:47
Show Gist options
  • Save atsea/641254ed1339e6f9aafa5117045d2a97 to your computer and use it in GitHub Desktop.
Save atsea/641254ed1339e6f9aafa5117045d2a97 to your computer and use it in GitHub Desktop.
JS - Create script tag to load JSON-D data for SEO
// JSON-D SCRIPT LOADING
// @see https://www.html5rocks.com/en/tutorials/speed/script-loading/
<link rel="subresource" href="//www.timothysofnewark.com/blog/js/tims-jsond.js">
<script type="text/javascript">
document.documentElement.className = 'js';
var scripts = [
'tims-jsond.js'
];
var src;
var script;
var pendingScripts = [];
var firstScript = document.scripts[0];
// Watch scripts load in IE
function stateChange() {
// Execute as many scripts in order as we can
var pendingScript;
while (pendingScripts[0] && pendingScripts[0].readyState == 'loaded') {
pendingScript = pendingScripts.shift();
// avoid future loading events from this script (eg, if src changes)
pendingScript.onreadystatechange = null;
// can't just appendChild, old IE bug if element isn't closed
firstScript.parentNode.insertBefore(pendingScript, firstScript);
}
}
// loop through our script urls
while (src = scripts.shift()) {
if ('async' in firstScript) { // modern browsers
script = document.createElement('script');
script.async = false;
script.src = src;
script.type = 'application/ld+json';
document.head.appendChild(script);
}
else if (firstScript.readyState) { // IE<10
// create a script and add it to our todo pile
script = document.createElement('script');
pendingScripts.push(script);
// listen for state changes
script.onreadystatechange = stateChange;
// must set src AFTER adding onreadystatechange listener
// else we’ll miss the loaded event for cached scripts
script.src = src;
}
else { // fall back to defer
document.write('<script src="' + src + '" defer></'+'script>');
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment