發表文章

目前顯示的是有「document」標籤的文章

前端優化效能-1(lazy-img)

圖片
在Chrome底下可以使用在img DOM加入 loading="lazy" 就可以直接使用懶加載了,或者裝線上有的plugin也可以的(但是我喜歡自己來) <img src="image.png" loading="lazy" alt="..." /> 但IE跟Safari是不支援這樣的語法的,所以只好自己幹一個了,我們來用 IntersectionObserver吧(結果IE 也沒支援attribute QAQ) //註冊在讀取圖檔時要做的事情 window.addEventListener('load', () => {      const watcher = new IntersectionObserver(onEnterView) const elementArrary = document.getElementsByClassName('your_imgName'); for (let image of elementArrary) { watcher.observe(image) // 開始監視 } } //IntersectionObserver 的call back function onEnterView(entries: IntersectionObserverEntry[], observer: IntersectionObserver) { for (let entry of entries) { if (entry.isIntersecting) { // Element show on the loadImage(entry.target) // cancel watch observer.unobserve(entry.target) } } } // load img logic function loadImage(img: HTMLImageElement) { const removeMockup = (