Search code examples
javascriptcross-browserexecution

Javascript block script execution


I need to do something like this:

  • Execute a piece of code
  • Start to load an image and block the script execution
  • When the image is loaded resume the execution
  • Execute the rest of the code

I know that the simplest way is to assign a function on the onload event of the image and then execute the rest of the code in the function, but if it's possible i want to have a "linear" behaviour blocking the script execution and then resume it. So, is there a cross-browser way to do this?


Solution

  • The only way to block script execution is to use a loop, which will also lock up most browsers and prevent any interaction with your web page.

    Firefox, Chrome, Safari, Opera and IE all support the complete property, which was finally standardised in HTML5. This means you can use a while loop to halt script execution until the image has finished downloading.

    var img = new Image();
    img.src = "/myImage.jpg";
    document.body.appendChild(img);
    while (!img.complete) 
    {
        // do nothing...
    }
    
    // script continues after image load
    

    That being said, I think you should look at ways of achieving your goal without locking up the browser.