Skip to content

Instantly share code, notes, and snippets.

@acbilimoria
Created January 17, 2016 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acbilimoria/0c1b850f0e8e6c3a950b to your computer and use it in GitHub Desktop.
Save acbilimoria/0c1b850f0e8e6c3a950b to your computer and use it in GitHub Desktop.
Script to call external javascript file
https://varvy.com/pagespeed/defer-loading-javascript.html
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "defer.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
Specific instructions
1. Copy above code.
2. Paste code in your HTML just before the </body> tag (near the bottom of your HTML file).
3. Change the "defer.js" to the name of your external JS file.
4. Ensure the path to your file is correct. Example: if you just put "defer.js", then the file "defer.js" must be in the same folder as your HTML file.
p.s. JS should be split into two groups: one that the page needs to load and another that can be fully deferred
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment