tags:

views:

43

answers:

3

Hi everyone,

The more i use JavaScript the more i try to come up with efficient ways of loading and executing my scripts. One method i have found to be really useful is loading javascript without blocking.

function include_js(url) { 
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

include_js('script.js');

JavaScript also has a window method that executes when the page has loaded.

window.onload = function() {
 alert('Script executed onload');
};

What i want to know is, how does the browser treat script executed by the window.onload method, is it blocking or non-blocking script?

A: 

What i want to know is, how does the browser treat script executed by the window.onload method, is it blocking or none-blocking script?

I think I don't really understand that part. window.onload is fired when all data was loaded (images, iframes + anything else).

This is not bound to script loading, at least not if you use dynamic script tag insertion. So it's asynchronous, to answer your question

Still you can attach your own onload handler to your script element by using

script.onload = function(){
    // loaded
};

or even better, to have it cross-browser

script.onload = script.onreadystatechange = function(){
     if(script.readyState){
        if(script.readyState === 'complete' || script.readyState === 'loaded'){
           script.onreadystatechange = null;
           // loaded
        }
     }
     else{
        // loaded
     }
};    
jAndy
Thanks a lot for your response, i'm trying to find the best practice that will help my page load faster, window.onload or appending my script via DOM.
Q_the_dreadlocked_ninja
+1  A: 

It is non-blocking. You are simply assigning a variable to a function and the execution of other script continues. Once the DOM is loaded the assigned callback is invoked.

Darin Dimitrov
+1  A: 

What i want to know is, how does the browser treat script executed by the window.onload method, is it blocking or non-blocking script?

Are you referring to how the code in the event handler is executed? It runs asynchronously, but since JavaScript only has one thread, it is blocks, and will be blocked itself until the thread is available.

See this article about how timers work to get a better idea of how asynchronous methods behave in single thread environment.

The only way to have JavaScript code that executes in parallel to other JavaScript code is to use web workers, which actually use a separate thread.

Justin Johnson
Thank you for the links, this is the answer i was looking for.
Q_the_dreadlocked_ninja