Skip to content

Instantly share code, notes, and snippets.

@Tusko
Last active September 27, 2020 09:51
Show Gist options
  • Select an option

  • Save Tusko/77a44b2d16d3ed722a9cb4abb168464b to your computer and use it in GitHub Desktop.

Select an option

Save Tusko/77a44b2d16d3ed722a9cb4abb168464b to your computer and use it in GitHub Desktop.
deferimg.js
function load_defer_img(source) {
'use strict';
return $.Deferred(function(task) {
var image = new Image();
image.onload = function() {
task.resolve(image);
};
image.onerror = function() {
task.reject();
};
image.src = source;
}).promise();
}
function loadlater() {
'use strict';
$('[data-defer]').each(function() {
var t = $(this),
pre = t.data('pre'),
img = t.data('defer');
$.when(load_defer_img(img)).done(function(image) {
t.removeAttr('data-defer');
if(t.is('img')) {
t.prop('src', img);
} else {
if(t.has('> img:not([data-defer])').length > 0) {
return;
}
if(typeof pre !== 'undefined') {
t.prepend(image);
} else {
t.append(image);
}
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment