Preload images on this script

Viewed 44

I'm using this script to load images on two of my sites (script is hosted on other site). Script loads on the website and place the image inside a div with the ID div-to-load-external-image

The problem is that PageSpeed Insights is telling me to preload these images and I don't have a clue how to do it...

Any help?

var imagesvar = [
["/goout/mylink/", "https://picsum.photos/300/145", "Title 1", "tracking-image"],
["/goout/mylink/", "https://picsum.photos/300/145", "Title 2", "tracking-image"],
["/goout/mylink/", "https://picsum.photos/300/145", "Title 3", "tracking-image"],
["/goout/mylink/", "https://picsum.photos/300/145", "Title 4", "tracking-image"],
];
function shuffle(b) {
    var j, x, i;
    for (i = b.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = b[i];
        b[i] = b[j];
        b[j] = x;
    }
    return b;
}
shuffle(imagesvar);
document.getElementById('div-to-load-external-image').innerHTML = '<a href="'+imagesvar[0][0]+'" target="_blank" rel="nofollow"><span class="myclass">New</span><div class="myimage" style="text-align:center;"><img src="'+imagesvar[0][1]+'" width="300px" height="145px" alt="'+imagesvar[0][3]+'" onClick="gtag(\'event\', \'TodNav\', {\'event_category\': \'tod\',\'event_label\': \'tod-'+imagesvar[0][3]+'\'});" /></div><h2 class="title">'+imagesvar[0][2]+'</h2></a>';
1 Answers

I think you can preload images in the <head> section of your HTML document using the following:

<html>
  <head>
    <link rel="preload" as="image" href="someImage">
  </head>
  <body>
    <img src="someImage">
  </body>
</html>

Found an interesting article you might want to read: https://web.dev/preload-responsive-images/

Related