Skip to content

Instantly share code, notes, and snippets.

@UziTech
Created March 13, 2015 21:57
Show Gist options
  • Save UziTech/0d139f9a812ef18b2723 to your computer and use it in GitHub Desktop.
Save UziTech/0d139f9a812ef18b2723 to your computer and use it in GitHub Desktop.
jQuery plugin to swap new image after it loads. Useful if you want to load low res image first then swap with high res after it loads.
/*
* DWTFYW License
*
* Author: Tony Brix, http://tonybrix.info
*
* Swap an image after it loads. Useful if you want to load low res image first then swap with high res after it loads.
*/
(function ($) {
$.fn.swapImage = function (img) {
var $this = this;
var image = new Image();
image.onload = function () {
var src = this.src;
$this.each(function () {
if ($(this).is("img")) {
this.src = src;
} else {
$(this).css({"background-image": "url('" + src + "')"});
}
});
};
image.src = img;
return this;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment