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: JAVASCRIPT, OpenSource
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.
[...] The best way to load javascript [...]