Skip to content

Instantly share code, notes, and snippets.

@pbojinov
Last active April 27, 2024 04:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pbojinov/7011269 to your computer and use it in GitHub Desktop.
Save pbojinov/7011269 to your computer and use it in GitHub Desktop.
Defer loading javascript until page loads. #perfmatters
//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