延迟加载图像 - 每秒最多 x

Lazy loading images - max x per second

要求

以每秒发出最多 x 个请求的方式加载包含 100 多张图像的页面上的所有图像,以避免达到速率限制器(允许来自同一 IP 的每秒最多 X 个请求)。

可能的解决方案

更改标记:

<img src="/someimage.jpg">

<img data-src="/someimage.jpg" class="lazyrate">

实现一个 javascript 将 class“lazyrate”的所有图像加载到一个数组中,将 data-src 替换为 src(加载图像)一个接一个(或批量) x), 中间有延迟,不会触发限速。

加载 5 张图片,等待 1 秒,加载 5 张下一张图片,等待 1 秒等

为了改善用户体验,将其与仅加载可见图像(传统延迟加载)相结合

问题

是否存在已经这样做的东西?就像具有限速功能的延迟加载插件?或者我应该采取另一种方法吗?

背景/“你为什么不...”

在强制限速的大型公司的内部网络应用程序中,显示大量图像(页面上 100 多张)的网络应用程序有时会触发限速,因为所有图像都是同时加载。

所以我最终写了一个简单的 jquery 插件来处理这个问题,并在 github 上分享了它。

https://github.com/kjlibsol/lazyrate

它不关心图像是否在屏幕上,因为对我来说 use-case 有就好了,不需要。

为了将来参考,这里是完整的源代码:

(function ($) {
    $.fn.lazyRate = function (options) {

        var settings = $.extend({
            delay: 200 //default (in ms)
        }, options);

        var sleepValue = 0;

        return this.each(function () {
            var realSrc = $(this).data("src"); //the value of the real image, we want to display
            var id = this.id; //the id of the image - needed to use setTimeout (which does not understand "this")
            setTimeout(
                function () {
                    $("#" + id).attr("src", realSrc); //replace the src with the value from data-src (to load the image)
                }, sleepValue);
            sleepValue = sleepValue + settings.delay; //increase the delay for each loop, as the setTimeout returns right away
        });
    };

}(jQuery));

用法:

在其中放置一些 data-src 带有真实图像的属性 - 并添加带有占位符图像的 src

<img id="img001" data-src="img/IMG_0032.jpg" src="img/placeholder.png" height="200" class="lazyrate">
<img id="img002" data-src="img/IMG_0037.jpg" src="img/placeholder.png" height="200" class="lazyrate">
...

现在 运行 添加了 class 上的插件 - 在这种情况下为 lazyrate:

    <script>
        $(document).ready(function () {
            $(".lazyrate").lazyRate();
        });
    </script>