如果互联网速度高加载图像或根本不加载

Em *_*dhu 2 javascript jquery image

我在SO中搜索了很多关于类似事情的问题。但似乎没有一个适合我的情况。

我有几个不同的背景图像。现在我根据背景图像手动创建渐变并将其设置为默认值。并在 3 秒后加载默认渐变的背景图像。

但我不想要这种方法。我只想在用户连接良好时才显示图像。或者根本不显示图像,让背景图像的渐变在那里。

代码示例:CSS

.test1 {
    background-image: -webkit-gradient(linear, 0 0, 86 148, color-stop(0.011, #898568));
    background-image: -webkit-linear-gradient(300.1600608380871deg, #898568 1.1%);
    background-image: -moz-linear-gradient(300.1600608380871deg, #898568 1.1%);
    background-image: -o-linear-gradient(300.1600608380871deg, #898568 1.1%);
    background-image: linear-gradient(149.83993916191292deg, #898568 1.1%)
}

.test1-img {
    background-image: url("img1.jpg");
}
Run Code Online (Sandbox Code Playgroud)

代码示例:JS

setTimeout(function() {

$('#test1-div').toggleClass('test1-img');

}, 3000);
Run Code Online (Sandbox Code Playgroud)

那么可以用 jQuery 或 JS 来做到这一点吗?或者有任何插件吗?

PS:我不想要延迟加载算法。因为即使用户的互联网连接速度较低,它也会在用户进入视口时加载图像。对我来说,我根本不想在低速连接时显示背景图像。

PS2:我是新的 JS,所以带有解释的工作解决方案非常适合我理解。

Mat*_*Sot 5

If you're OK with attempting to load a single image, you could try something like the following:

window.speedyConnection = false;

var image = document.createElement("img");
image.onload = function () {
    window.speedyConnection = true;
    //Load your images here
}
image.src = "img1.jpg";

setTimeout(function () {
    if (!window.speedyConnection) {
        image.remove();
    }
}, 750);
Run Code Online (Sandbox Code Playgroud)

The idea being that you attempt to load the first image, but if it doesn't load in 750ms (or whatever timeout you prefer) you assume the user has a bad connection and stop loading it. If it does load, you go ahead and load the rest of the images.

This would, however, require at least sending a request for an image and receiving some data (even on slow connections), but it would only be for a single image and you would cancel it after the timeout.