How to defer load Javascripts

Apanha

Staff member
 
24,549
869
3,191
When it comes to optimizing page speed, as a general rule you should aim to remove all Javascripts your web pages
Please, Log in or Register to view content!
. When you do need one for a certain aspect that can be replaced with CSS (like visual effects) you should try to replace the effect or function the Javascript helps you with with CSS.

Defer loading javascripts
When defer loading Javascripts you basically tell the browser to load the Javascripts after a web page (the DOM) has finished loading. This allows the browser to load the most important visual parts of your web page first so a quick initial view of the above the fold content can be shown, which can be defined by your
Please, Log in or Register to view content!
. Deferring scripts this way makes the page load more quickly but without the average user even realizing some Javascripts are loaded after the DOM has loaded. You can do the same
Please, Log in or Register to view content!
, which is also recommended.

Find Javascripts which aren't required for the initial view
Many Javascripts, for example Javascripts that are used for user-interactive or visual functions, can be loaded after the DOM has loaded and still perform their function. You don’t actually need to load these Javascripts to load the
Please, Log in or Register to view content!
of a page. However, your web pages may load a few Javascripts that are required to load the initial view content of a page.
Find out which Javascripts your web pages don't need for the initial above-the-fold view and copy & paste all of them in a single Javascript (.js ) file.

The recommended way of defer loading Javascripts
The easiest, and most recommended way is using this simple HTML defer script snippet to call a Javascript file:
<script defer="defer" src="yourscript.js"></script>
Replace yourscript.js with the .js file you created in the step before this one and place the above snippet in the HTML footer. By using the above snippet on your web page you tell the browser to load the yourdeferscripts.js file after your web page has finished loading.

Another way

Add the following small code to the bottom of your web page just above the closing </body> tag and replace yourscript.js with your Javascript file:
<script type="text/javascript"> function downloadJSAtOnload() { var element = document.createElement("script"); element.src = "yourscript.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>
 

Create an account or login to comment

You must be a member in order to leave a comment

Create account

Create an account on our community. It's easy!

Log in

Already have an account? Log in here.

Top Bottom