Last active
April 13, 2020 16:05
-
-
Save crates/cb6adb1c382026ad2e57f2f498d8967e to your computer and use it in GitHub Desktop.
Vanilla JavaScript method for loading a script into your document
This file contains hidden or 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
function getScript(url, success = () => {}, async = true, defer = false, attributes) { | |
var debugMode = debugMode || Boolean(window.console && console && ( | |
Boolean(window.location.href.indexOf('localhost')+1) || | |
Boolean(window.location.href.indexOf('dev.')+1) | |
)), | |
script = document.createElement('script'), | |
deferLoadFunc = function() { | |
script.src = url; | |
script.type = 'text/javascript'; | |
if (async) script.async = true; | |
if (defer) script.defer = true; | |
var head = document.getElementsByTagName('head')[0], done = false; | |
script.onload = script.onreadystatechange = function() { // Attach handlers for all browsers | |
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { | |
done = true; | |
if (typeof success === 'function') success(); | |
script.onload = script.onreadystatechange = null; | |
// if (debugMode) { | |
// console.log('Script fully loaded... removing now:'); | |
// console.log(script); | |
// } | |
// document.body.removeChild(script); | |
} | |
}; | |
if (attributes) { | |
for (k in attributes) { | |
if (attributes.hasOwnProperty(k)) { | |
script.setAttribute(k, attributes[k]); | |
} | |
} | |
} | |
if (debugMode) { | |
console.log('Inserting script tag with async=' + async + ' and defer=' + defer + ':'); | |
console.log(script); | |
} | |
document.body.appendChild(script); | |
}; // deferLoadFunc() | |
if (defer) { // Load a call AFTER all page resources are loaded: | |
if (window.addEventListener) window.addEventListener('load', deferLoadFunc, false); | |
else if (window.attachEvent) window.attachEvent('onload', deferLoadFunc); | |
else window.onload = deferLoadFunc; | |
} else if (async) setTimeout(deferLoadFunc, 57); // <-- don't defer, but keep it non-blocking | |
else deferLoadFunc(); // <-- some calls actually WANT to be loaded sequentially | |
} // getScript(url, success) | |
// SAMPLE INVOCATION: | |
// getScript('//code.jquery.com/jquery-3.4.1.min.js', null, false, false, { | |
// 'data-foo': 'bar' | |
// }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script is lacking any detection or protection to ensure that the same script isn't loaded multiple times.
I think I've got some code somewhere that I can add to this routine to make it do that properly.