Technicalarticles
如果你的网站使用JavaScript来显示内容或向用户提供某种功能,则快速加载DOM变得至关重要。脚本通常要等到DOM完全加载后才能开始运行。在包含大量图像的网站上,延迟加载(或异步加载图像)可能会导致用户停留或离开你的网站有所不同。
由于大多数惰性加载解决方案都是通过仅在用户滚动到在视口内可见图像的位置时才加载图像来工作的,因此如果用户从未到达该点,则将永远不会加载这些图像。这意味着可以节省大量带宽,为此,大多数用户,特别是那些在移动设备上访问Web且连接缓慢的用户,将非常感谢你。
<img src="myimage.jpg" loading="lazy" alt="..." /><iframe src="content.html" loading="lazy"></iframe>
lazy:非常适合延迟加载
eager:指示浏览器立即加载指定的内容
auto:保留延迟加载或不延迟加载到浏览器的选项。
Intersection Observer API提供了一种异步观察目标元素与祖先元素或顶级文档的视口相交的变化的方法。
<img data-src="image.jpg" alt="test image">
img { min-height: 100px; /* more styles here */}
// create config object: rootMargin and threshold
// are two properties exposed by the interface
const config = {
rootMargin: '0px 0px 50px 0px',
threshold: 0
};
// register the config object with an instance
// of intersectionObserver
let observer = new intersectionObserver(function(entries, self) {
// iterate over each entry
entries.forEach(entry => {
// process just the images that are intersecting.
// isIntersecting is a property exposed by the interface
if(entry.isIntersecting) {
// custom function that copies the path to the img
// from data-src to src
preloadImage(entry.target);
// the image is now in place, stop watching
self.unobserve(entry.target);
}
});
}, config);
const imgs = document.querySelectorAll('[data-src]');imgs.forEach(img => { observer.observe(img);});
npm install --save lozadyarn add lozad
import lozad from 'lozad';
<script src="https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js"></script>
<img data-src="img.jpg">
const observer = lozad();observer.observe();
性能:仅463字节的CSS和1,007字节的最小JavaScript代码
支持视网膜屏幕
无依赖关系:不需要jQuery或其他库和框架
逐步增强功能以抵消较旧的浏览器和JavaScript失败
<script src="yall.min.js"></script><script> document.addEventListener("DOMContentLoaded", yall);</script>
<img src="placeholder.jpg" data-src="image-to-lazy-load.jpg" alt="Alternative text to describe image.">
你将懒惰的类添加到元素
src的值是一个图像占位符
你要延迟加载的图像的路径在data-src属性内部
Intersection Observer API的出色性能
出色的浏览器支持(可回溯到IE11)
无需其他依赖项
英文 | https://www.geeksforgeeks.org/how-to-create-dark-light-mode-for-website-using-javascript-jquery/?ref=leftbar-rightbar
DO U LIKE?