Delay Loading Assets

There are some cases where there are images not loaded whenever a page is opened. For example, when an image changes on a hover event, the image isn’t loaded until the first time the mouse cursor is brought to its location. As such, some users may be confused when the image disappears for a moment as the image is loading.

I would like to introduce two methods for handling this situation.

 

Using the link tag

 

If you are planning on using that image later on the same page, you can add it to a link tag in your HTML.

<link href='images.jpg' rel='preload'>

 

For rel, there are the attributes preload and prefetch. If you would like to load the image as quickly as possible, you should use preload. If it is fine to wait a little longer before loading it, prefetch should be used.

With this, you can solve the problem mentioned above. This method only uses HTML so it is easy to implement, but it is syncronous, so it will load the image before the page is displayed which increases the page load time, so I would also like to introduce an asyncronous method.

 

Lazy Loading

 

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var link = document.createElement('link');
    link.rel = 'jpg';
    link.href = url;
  }
};
xhr.send();

 

Bonus

 

Using the example above, if you need to load various different filetypes, you will need a separate function for each one, so I will also introduce how to load any filetype with just one function.

function loadAsset (asset) {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.returnType = asset.type;
        xhr.onload = function () {
            var link = document.createElement('link');
            link.rel = asset.rel;
            link.href = asset.url;
            document.head.appendChild(link);
            resolve();
        };
        xhr.onerror = reject;
        xhr.open('get', asset.url);
        xhr.send();
    });
}
document.body.onload = function() {
    var assets = [
        {url:'image.png',type:'image',rel: 'png'},
        {url:'image.jpg',type:'image',rel: 'jpg'},
        {url:'image.gif',type: 'image',rel: 'gif'},
        {url:'font.css',type: 'text',rel: 'stylesheet'}
    ];
    assets.forEach(function(asset){
        loadAsset(asset);
    });
}

 

Using these methods, the images can be loaded smoothly without causing any confusion for your users.