Created
February 26, 2011 11:56
-
-
Save johndwells/845145 to your computer and use it in GitHub Desktop.
This snippet includes all of the boilerplate code to attach a load event to an image. Provisions are included for an image already loaded into browser's cache.
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
var img = new Image(); | |
$(img) | |
// set the src attribute of the new image to our image | |
.attr('src', '/path/to/image.jpg') | |
// once the image has loaded, execute this code | |
.one('load', function () { | |
// remember to place into DOM first if you need access to width & height | |
// access width & height with this.width and this.height | |
}) | |
// if there was an error loading the image, you can do something here | |
.error(function () {}) | |
// if image is already cached in browser, trigger load manually if necessary | |
// updated with code from https://gist.github.com/797120/7176db676f1e0e20d7c23933f9fc655c2f120c58 | |
.each(function() { | |
if (this.complete || this.complete === undefined){ | |
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f | |
// data uri bypasses webkit log warning (thx doug jones) | |
var src = this.src; | |
this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; | |
this.src = src; | |
$(this).trigger('load'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment