Preloading images with JavaScript

后端 未结 14 1046
太阳男子
太阳男子 2020-11-22 03:17

Is the function I wrote below enough to preload images in most, if not all, browsers commonly used today?

function preloadImage(url)
{
    var img=new Image(         


        
相关标签:
14条回答
  • 2020-11-22 03:59

    The browser will work best using the link tag in the head.

    export function preloadImages (imageSources: string[]): void {
      imageSources
        .forEach(i => {
          const linkEl = document.createElement('link');
          linkEl.setAttribute('rel', 'preload');
          linkEl.setAttribute('href', i);
          linkEl.setAttribute('as', 'image');
          document.head.appendChild(linkEl);
        });
    }
    
    0 讨论(0)
  • 2020-11-22 04:00

    Try this I think this is better.

    var images = [];
    function preload() {
        for (var i = 0; i < arguments.length; i++) {
            images[i] = new Image();
            images[i].src = preload.arguments[i];
        }
    }
    
    //-- usage --//
    preload(
        "http://domain.tld/gallery/image-001.jpg",
        "http://domain.tld/gallery/image-002.jpg",
        "http://domain.tld/gallery/image-003.jpg"
    )
    

    Source: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

    0 讨论(0)
提交回复
热议问题