The best way to load javascript

Posted By Venu Thomas

Nicholas C. Zakas has been thinking about the issue and has taken 3 points needed to be taken to improve the load javascript on our pages.

* Create two files Javascript. In the first place you need to dynamically load another javascript file and the second with the code needed for our application.
* Javascript includes the first end of the page just above < / body >
* Just below we create a second tag < script > where to call / the file / s needed.

Our HTML would be more or less like this:

<script type="text/javascript" src="http://your.cdn.com/first.js"></script>
<script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
//initialization code
});
</script>

loadScript ()

loadScript () function is responsible for loading the Javascript file in a dynamic and responsible for implementing the code as the second parameter to indicate when it is loaded correctly.

function loadScript(url, callback){

var script = document.createElement("script")
script.type = "text/javascript";

if (script.readyState){  //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else {  //Others
script.onload = function(){
callback();
};
}

script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}

Clearly, these optimizations improve outcome, although we are talking about milliseconds (or seconds in the worst case). But it’s good to know how to improve our scripts and pulirlos well.

Happy Programming!!! ;)

Tags: ,

  •  
  • Share with others:

    Thanks for visiting us! If you enjoyed these icons please feel free to share them! Or if you want to know what's going on with WiseCodes.com, follow us!

    2 Responses to “The best way to load javascript”

    1. well on the first case mentioning type is not necessary, browser relies on the server for the type. Most of the people do but just a info.

    2. Prashanth your flag on August 12th, 2009 at 5:00 PM
    3. [...] The best way to load javascript [...]

    4. 網站製作學習誌 » [Web] 連結分享 your flag on August 13th, 2009 at 10:21 AM

    Leave a Reply

    Anti-Spam Protection by WP-SpamFree

    Locations of visitors to this page eXTReMe Tracker