Last active
September 27, 2020 09:51
-
-
Save Tusko/77a44b2d16d3ed722a9cb4abb168464b to your computer and use it in GitHub Desktop.
deferimg.js
This file contains hidden or 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
| 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