Created
December 7, 2011 13:51
-
-
Save Integralist/1442875 to your computer and use it in GitHub Desktop.
image onload event issue when browser caches image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Had issue with browsers caching images and so they were not triggering an onload event. | |
* This jQuery snippet helped fixed the issue. | |
* | |
* UPDATE: | |
* Discovered that IE9 was having issues (IE7/8 were fine?) | |
* So we used a 'cache-buster' technique which is to append a QueryString onto the end of the image URL | |
*/ | |
var originalSource, | |
imageList = $('img'); | |
/* | |
* Following function expression indicates whether the current rendering engine is Trident (i.e. Internet Explorer) | |
* | |
* @return v { Integer|undefined } if IE then returns the version, otherwise returns 'undefined' to indicate NOT a IE browser | |
*/ | |
var isIE = (function() { | |
var undef, | |
v = 3, | |
div = document.createElement('div'), | |
all = div.getElementsByTagName('i'); | |
while ( | |
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', | |
all[0] | |
); | |
return v > 4 ? v : undef; | |
}()); | |
// If we're not using IE then we can use the img.complete property to determine if image is loaded | |
if (!isIE) { | |
// Execute the 'load' event only once | |
$(imageList).one('load', function() { | |
// Do stuff on image load | |
}) | |
// Loop through each image found | |
.each(function() { | |
// Check if the image 'complete' property has been set to true | |
// See: https://developer.mozilla.org/en/DOM/HTMLImageElement#DOM_properties | |
if(this.complete) { | |
// Trigger the load event for each image | |
$(this).load(); | |
} | |
}); | |
} else { | |
// Loop through each image found | |
$(imageList).each(function(){ | |
// Keep a reference to the original src | |
originalSource = this.src; | |
// Reset the src attribute so it includes a QueryString (this is the 'cache-buster' technique) | |
this.src = originalSource + '?' + new Date().getTime(); | |
}).on('load', function(){ | |
// Do stuff on image load | |
}); | |
} |
thanks @millermediros I'll check that out :-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this might be useful: https://github.com/desandro/imagesloaded (check source comments)