'If Internet Speed is high load images or dont load at all

I searched so many questions in SO about similar things. But none seems to work for my situation.

I have several diffent background images. For now i created gradient based on the background image manually and set it default. And loading the background image over the default gradient after 3 seconds.

But i dont want this kind of approach. I want to display images only if the user has good connection. Or else dont display the image at all, let the gradient of that background image be there.

Code example: 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");
}

Code Sample: JS

setTimeout(function() {

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

}, 3000);

So Is it possible to do this in jQuery or JS? or any plugin for this?

PS: I dont want lazy loading algorithm. Cause it loads images when user comes into viewport even if they have low internet connection. For me i dont want to display background image at all for low speed connection.

PS2: I am new JS, so with working solutions with explanation is very good for me to understand.



Solution 1:[1]

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);

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.

Solution 2:[2]

try navigator.connection.effectiveType, you'll pretty much get what you want. it's going to show '2g', '3g', '4g' or '5g'. check browser compat too, see if you're okay with it

https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MatthewSot
Solution 2 Karlus da Wakoko