Javascript block script execution

I need to do something like this:

  • Execute code snippet
  • Start loading image and block script execution
  • When the image loads, resume execution
  • Execute the rest of the code

I know that the easiest way is to assign a function in the onload event of the image, and then execute the rest of the code in the function, but if possible, I want to have a “linear” behavior that blocks script execution and then resume it. So, is there a cross-browser way to do this?

+5
source share
5 answers

script - , -.

Firefox, Chrome, Safari, Opera IE complete, , , HTML5. , while script .

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

// script continues after image load

, , , .

+3

, Javascript,

image.onload = new EventNotifier();
image.onload.wait->();
+1

, , .

CSS , . , CSS DIV, , . . ( ), CSS; . , , ?

+1

script, , script .

, "" , . - , .

:

var _img = null; 
var _imgDelay = 0;
var _finished = false;

function startWork(){
   _img = document.createElement('img');
   _img.onload = onImgLoaded;
   _img.src = 'yourimg.png';

   // append img tag to parent element here

   // this is a time out function in case the img never loads,
   // or the onload event never fires (which can happen in some browsers) 
   imgTimeout();   
}

function imgTimeout(){
   if (_img.complete){
      // img is really done loading
      finishWork();
   }
   else{
      // calls recursively waiting for the img to load
      // increasing the wait time with each call, up to 12s
      _imgDelay += 3000;

      if (_imgDelay <= 12000){ // waits up to 30 seconds
         setTimeout(imgTimeout, _imgDelay);
      }
      else{
         // img never loaded, recover here.
      }
   }
}

function onImgLoaded(){
   finishWork();
}

function finishWork(){
   if (!_finished){
      // continue here
      _finished = true;
   }
}
+1

xmlhttprequest .

var url = "image.php?sleep=3";
var img = new Image;
var sjax = new XMLHttpRequest();
img.src = url;
sjax.open("GET", url, false);
sjax.send(null);
alert(img.complete);

, Image, ajax . Image , , . , ajax , . , Image.

This assumes the image is served with HTTP caching headers. Otherwise, this behavior may vary across browsers.

+1
source

All Articles