Tag: Asynchrnous

Lazyload (Asynchronous loading) your javascript files

An alternative to putting scripts on the bottom, is to lazyload your scripts. To lazyload your scripts there are three ways i want to show you. First you can write your own little script that will asynchronously load your main javascript file by inserting the script tag for that file programmatically. Second possibility is to use a tool like require.js which is an asynchronous scripts downloader. The thrid possibility is the new HTML5 attribute for the script tag that you can use to force the browser to load the script asynchronously.

Lazyloading a javascript file default

You can create your own basic lazyloader yourself. Only a few lines of javascript in the head of your document and your done:


function lazyload() {
    var scriptTag = document.createElement('script'); 
    scriptTag.src = "//my_example.js"; // set the src attribute
    scriptTag.type = 'text/javascript'; // if you have an HTML5 website you may want to comment this line out
    scriptTag.async = true; // the HTML5 async attribute
    var headTag = document.getElementsByTagName('head')[0];
    headTag.appendChild(scriptTag);
}
  • First
  • Previous
  • 1
  • Next
  • Last