Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preloading images in Javascript

I have created a simple photo gallery viewer, and I would like to preload the images in the background, and then run a function when they are done.

My question is, how do I do that?

like image 350
guyzyl Avatar asked Oct 17 '25 20:10

guyzyl


1 Answers

To preload an image use the <link> tag and add preload to the rel-attribute:

<link rel=preload href=path/to/the/image.jpg as=image>

Alternatively in Javascript:

var preImg = document.createElement('link')
preImg.href = 'path/to/image.jpg'
preImg.rel = 'preload'
preImg.as = 'image'
document.head.appendChild(preImg)

The preload value of the element's rel attribute allows you to write declarative fetch requests in your HTML , specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. This ensures that they are made available earlier and are less likely to block the page's first render, leading to performance improvements.

Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content

like image 75
Thielicious Avatar answered Oct 19 '25 11:10

Thielicious