将基于jQuery的惰性图像加载更新到IntersectionObserver

Five years ago I implemented "lazy loading" of the 600+ images on my podcast's archives page (I don't like paging, as a rule) over here https://www.hanselminutes.com/episodes. I did it with jQuery and a jQuery Plugin. It was kind of messy and gross from a purist's perspective, but it totally worked and has easily saved me (and you) hundreds of dollars in bandwidth over the years. The page is like 9 or 10 megs if you load 600 images, not to mention you're loading 600 freaking images.

五年前,我在https://www.hanselminutes.com/episodes的播客存档页面(通常不喜欢分页)上实现了600幅图像的“延迟加载”。 我是用jQuery和jQuery插件完成的。 从纯粹主义者的角度来看,这有点杂乱无章,但是它完全可以正常工作,并且多年来轻松地为我(和您)节省了数百美元的带宽。 如果加载600张图像,该页面就像9或10兆,更不用说您加载600张怪胎图像。

Fast-forward to 2018, and there's the "Intersection Observer API" that's supported everywhere but Safari and IE, well, because, Safari and IE, sigh. We will return to that issue in a moment.

快进到2018年,除了Safari和IE之外,到处都支持“ Intersection Observer API ”,因为Safari和IE令人叹为观止。 我们将在稍后讨论该问题。

Following Dean Hume's blog post on the topic, I start with my images like this. I don't populate src="", but instead hold the Image URL in the HTML5 data- bucket of data-src. For src, I can use the nothing grey.gif or just style and color the image grey.

Dean Hume关于该主题的博客文章之后,我从这样的图像开始。 我没有填充src =“”,而是将Image URL保留在data-srcHTML5数据桶中。 对于src,我可以不使用grey.gif,也可以仅使用样式和颜色为图像加灰色。

<a href="/626/christine-spangs-open-source-journey-from-teen-oss-contributor-to-cto-of-nylas" class="showCard">
    <img data-src="https://images.hanselminutes.com/images/626.jpg" 
         class="lazy" src="/images/grey.gif" width="212" height="212" alt="Christine Spang&#x27;s Open Source Journey from Teen OSS Contributor to CTO of Nylas" />
    <span class="shownumber">626</span>                
    <div class="overlay title">Christine Spang&#x27;s Open Source Journey from Teen OSS Contributor to CTO of Nylas</div>
</a>
<a href="/625/a-new-sega-megadrivegenesis-game-in-2018-with-1995-tools-with-tanglewoods-matt-phillips" class="showCard">
    <img data-src="https://images.hanselminutes.com/images/625.jpg" 
         class="lazy" src="/images/grey.gif" width="212" height="212" alt="A new Sega Megadrive/Genesis Game in 2018 with 1995 Tools with Tanglewood&#x27;s Matt Phillips" />
    <span class="shownumber">625</span>                
    <div class="overlay title">A new Sega Megadrive/Genesis Game in 2018 with 1995 Tools with Tanglewood&#x27;s Matt Phillips</div>
</a>

Then, if the images get within 50px intersecting the viewPort (I'm scrolling down) then I load them:

然后,如果图像与viewPort相交的像素在50像素之内(我向下滚动),则我将其加载:

// Get images of class lazy
const images = document.querySelectorAll('.lazy');
const config = {
  // If image gets within 50px go get it
  rootMargin: '50px 0px',
  threshold: 0.01
};

let observer = new IntersectionObserver(onIntersection, config);
  images.forEach(image => {
    observer.observe(image);
  });

Now that we are watching it, we need to do something when it's observed.

现在我们正在观看它,我们需要在观察到它时做些事情。

function onIntersection(entries) {
  // Loop through the entries
  entries.forEach(entry => {
    // Are we in viewport?
    if (entry.intersectionRatio > 0) {

      // Stop watching and load the image
      observer.unobserve(entry.target);
      preloadImage(entry.target);
    }
  });
}

If the browser (IE, Safari, Mobile Safari) doesn't support IntersectionObserver, we can do a few things. I *could* fall back to my old jQuery technique, although it would involve loading a bunch of extra scripts for those browsers, or I could just load all the images in a loop, regardless, like:

如果浏览器(IE,Safari,移动Safari)不支持IntersectionObserver,我们可以做一些事情。 我可以*回到我以前的jQuery技术,尽管它会涉及为这些浏览器加载一堆额外的脚本,或者我可以循环加载所有图像,无论如何:

if (!('IntersectionObserver' in window)) {
    loadImagesImmediately(images);
} else {...}

Dean's examples are all "Vanilla JS" and require no jQuery, no plugins, no polyfills WITH browser support. There are also some IntersectionObserver helper libraries out there like Cory Dowdy's IOLazy. Cory's is a nice simple wrapper and is super easy to implement. Given I want to support iOS Safari as well, I am using a polyfill to get the support I want from browsers that don't have it natively.

Dean的示例都是“ Vanilla JS”,不需要jQuery,不需要插件,不需要带有浏览器支持的polyfills。 还有一些IntersectionObserver帮助程序库,例如Cory Dowdy的IOLazy 。 Cory是一个很好的简单包装器,非常容易实现。 鉴于我也想支持iOS Safari,因此我正在使用polyfill从本地没有它的浏览器中获得所需的支持。

<!-- intersection observer polyfill -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script>

Polyfill.io is a lovely site that gives you just the fills you need (or those you need AND request) tailored to your browser. Try GETting the URL above in Chrome. You'll see it's basically empty as you don't need it. Then hit it in IE, and you'll get the polyfill. The official IntersectionObserver polyfill is at the w3c.

Polyfill.io是一个可爱的网站,它为您提供量身定制的,适合您浏览器的填充(或您需要和请求的填充)。 尝试在Chrome中获取上面的URL。 您会看到它基本上是空的,因为您不需要它。 然后在IE中点击它,您将获得polyfill。 官方的IntersectionObserver polyfill在w3c上

At this point I've removed jQuery entirely from my site and I'm just using an optional polyfill plus browser support that didn't exist when I started my podcast site. Fewer moving parts means a cleaner, leaner, simpler site!

现在,我已经从网站上完全删除了jQuery,而我只是在使用可选的polyfill加浏览器支持,而这在我启动播客网站时并不存在。 更少的活动部件意味着更清洁,更精简,更简单的场地!

Go subscribe to the Hanselminutes Podcast today! We're on iTunes, Spotify, Google Play, and even Twitter!

立即订阅Hanselminutes播客! 我们在iTunesSpotifyGoogle Play甚至Twitter上

翻译自: https://www.hanselman.com/blog/updating-jquerybased-lazy-image-loading-to-intersectionobserver

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值