javascriptimage-preloader

Is there an advantage to using web workers to pre-load images?


I am currently researching better ways to accomplish pre-loading of images and thought perhaps using web workers would be a more ideal way. However, I am not sure that it is. Is there any specific benefit in terms of performance and user experience using background workers versus classic-style pre-loading? Which is better?

function preloadBackground(a) {
    new d(window.URL.createObjectURL(
            new Blob([
            "(function () {" +
                "var x = new XMLHttpRequest();" +
                "x.responseType = 'blob';" +
                "x.open('GET', '" + a + "', true);" +
                "x.send();" +
            "}());\n"], { type: "text/javascript" })
            )
        )
}

function preloadClassic(a) {
    var i = new Image();
    i.src = a;
}

Solution

  • You can pre-load images easily with web-workers and hide them until you are ready to display them. This increases page load speed and reduces jank so that the flow is seamless between click and load.

    The main benefits to Pre-loading an image are usually seen when transitioning between a menu to a page with desired content, say a map or the next image in a slideshow or something similar. If you have a click event that takes a user to a picture then it's beneficial to pre-load. If you are testing with google's page speed insights you will notice a huge performance increase as well with a pre-load vs conventional load when clicked functionality.

    Check out this code over at Github, I think you may find it useful.

    If the image is loaded using a web-worker you avoid blocking the DOM construction so assigning a web worker to load the image when it's ready rather than when the rest of the page is will be helpful too, but that doesn't sound like pre-loading to me but rather an order of operations assignment. If the image isn't the content but rather the background it is unnecessary to make it DOM build blocking. Using a web-worker in this case is better.