Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript preload images

/* 
  Standards friendly image preloading
  Generates `<link rel="preload" as="image" href="important_image.png">`
  Ref: https://web.dev/preload-responsive-images/#preload-overview
*/
 
function preloadImages(images) {
  for (i = 0; i < images.length; i++) {
    let l = document.createElement('link')
    l.rel = 'preload'
    l.as = 'image'
    l.href = images[i]
    document.head.appendChild(l)
  }
}

// Usage:
imageUrlHeap = ['http://example.com/test/img-1.jpg','http://example.com/test/img-2.jpg','http://example.com/test/img-3.jpg'];
preloadImages(imageUrlHeap);
 
PREVIOUS NEXT
Tagged: #javascript #preload #images
ADD COMMENT
Topic
Name
8+6 =