Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created December 7, 2011 13:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/1442875 to your computer and use it in GitHub Desktop.
Save Integralist/1442875 to your computer and use it in GitHub Desktop.
image onload event issue when browser caches image
/*
* 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
});
}
@millermedeiros
Copy link

this might be useful: https://github.com/desandro/imagesloaded (check source comments)

@Integralist
Copy link
Author

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