Created
August 2, 2018 04:14
-
-
Save letswritetw/084f07341d6bae554ba9b90c413f1bbc to your computer and use it in GitHub Desktop.
像Medium的漸近式圖片加載
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
$(window).on('load', () => { | |
// 自由尺寸,先處理 padding-bottom | |
if($('.w-free').length > 0) { | |
$('.w-free').each(function() { | |
const w = $(this).find('.js-get-img').data('width'), | |
h = $(this).find('.js-get-img').data('height'), | |
pd = (h / w) * 100; | |
$(this).find('.js-get-img').css('paddingBottom', pd + '%'); | |
}); | |
} | |
// 監聽 scroll,加載圖片 | |
$('.lazy-image').each(function() { | |
const self = $(this); | |
const waypoint = new Waypoint({ | |
element: self[0], | |
handler() { | |
const src = self.find('.js-get-img').data('img'); // 抓原始圖路徑 | |
// 建立物件 | |
const img = new Image(); | |
img.src = src; | |
// 圖片載入完,append 進 div 裡 | |
$(img).on('load', () => { | |
self.find('.js-get-img').append(img); | |
setTimeout(function(){ | |
self.find('.js-get-img').addClass('show'); | |
}, 50); | |
}); | |
// destroy 該 div 的監聽 scroll | |
this.destroy(); | |
}, | |
offset: '75%' | |
}); | |
}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment