0

This maybe a real stupid question so I apologise and i stand ready to delete my own question.

I have an image element in my HTML5 app to which i give an id of 'img1' like so:

<img id="img1" src="" /`>

I assign a module variable to this element like so:

var staticImgArray = document.getElementById('img1');

I set the image src by binding it to a Generic handler (I am using ASP.NET)

staticImgArray .src = 'get image from this link';

Now I need to know at what point has the image finished loading. At the moment I use this code to determine that:

staticImgArray.onload = function () {
   //image has loaded
};
staticImgArray.onerror = function () {
   //image has not loaded properly but has finished trying?
};

But...

staticImgArray.src = 'get image from this link';
**//image has finished loading here..??**

//other code runs here afterwards

...if the above statement is not true then does that not imply the loading of the image is done asynchronously?

Thanks

scniro
  • 16,844
  • 8
  • 62
  • 106
Andrew Simpson
  • 6,883
  • 11
  • 79
  • 179

1 Answers1

1

The loading is async. Here is a working example that shows the onload callback firing after image loaded but js execution will not be stopped

fiddle


var staticImgArray = document.getElementById('img1');

staticImgArray.onload = function () {
   //other code after image loads runs here

    console.log('loaded');
};

staticImgArray.src = 'http://static.adzerk.net/Advertisers/c050fce5e0094decb57fdb53f4ca4254.jpg'

console.log('I fire first though');
scniro
  • 16,844
  • 8
  • 62
  • 106
  • Hi, thanks for that. I looked at the links sent by the other poster and it implies that you cannot always rely on th 'onload' event to work? – Andrew Simpson Dec 18 '14 at 13:41
  • Quick test in Chrome, FF, IE9+ shows it's working. See what works for you though. Reading through that SO post, this still seems like a reasonable way to go about this – scniro Dec 18 '14 at 13:49