Preloading images with JavaScript

后端 未结 14 1217
太阳男子
太阳男子 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);
        });
    }
    

提交回复
热议问题