Skip to content

Instantly share code, notes, and snippets.

@0xjjpa
Forked from pbojinov/defer.javascript.load.js
Created February 10, 2014 11:00
Show Gist options
  • Save 0xjjpa/8913936 to your computer and use it in GitHub Desktop.
Save 0xjjpa/8913936 to your computer and use it in GitHub Desktop.
//Add this at the bottom of your page right before </body>
//Will let the page content load before loading js
//Make sure you don't have critical js necessary for loading the page when using this because it will break it
function downloadJSOnload() {
var element = document.createElement('script');
element.setAttribute('src', 'a.js');
document.body.appendChild(element);
}
if (window.addEventListener) {
window.addEventListener('load', downloadJSOnload, false);
}
else if (window.attachEvent) {
window.attachEvent('onload', downloadJSOnload);
}
else {
window.onload = downloadJSOnload;
}
//download multiple files
//use for loop to avoid polyfilling forEach on older browsers
function downloadAllJSOnload() {
var scripts = ["static/js/a.js", "static/js/b.js"];
for (var i = 0, len = scripts.length; i < len; i++) {
var element = document.createElement("script");
element.setAttribute('src', scripts[i]);
document.body.appendChild(element);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment