SoFunction
Updated on 2025-04-12

Summary of the method of implementing image preloading in JavaScript

1. Basic concepts and functions of image preloading

In web front-end development, images are an important part of web page content, but their loading time often affects the overall performance of the page. In order to improve user experience and reduce waiting time, developers usually use Image Preloading technology. The so-called image preloading means that before the user actually accesses it, the image resources are loaded into the browser cache in advance, so that when the user browses these images, they can be displayed immediately without requesting them from the server again.

Advantages of preloading images

  • Improve user experience: By loading pictures in advance, it can be ensured that the pictures can be presented quickly when the user scrolls the page or clicks on the link, avoiding white screen or flickering.
  • Optimize SEO: Search engine crawlers prefer websites that are fast-loaded and rich in content. Good image loading speed helps improve the search engine ranking of the website.
  • Save bandwidth: For mobile device users, preloading can be done in a Wi-Fi environment, thereby reducing unnecessary data transmission under mobile networks and saving traffic costs.
  • Enhance interaction effect: Combined with JavaScript animation or transition effects, preloading can make image switching smoother and more natural, and enhance visual impact.

2. Methods to implement image preloading using JavaScript

Method 1: Create <img> element and set the src attribute

This is the easiest and most direct way to create dynamically<img>Tag and assign the URL of the target image tosrcProperties, trigger the browser to download the image. Although this approach is simple and easy to use, it also has some limitations, such as not being able to listen for load progress or handling error conditions.

Example 1: Preload using <img> element

function preloadImages(imageUrls) {
  (url =&gt; {
    const img = new Image();
     = url;
  });
}

// Use exampleconst imageUrls = [
  '/',
  '/',
  '/'
];
preloadImages(imageUrls);

Method 2: Utilize Promise and fetch API

With the introduction of the ES6 standard, Promise and fetch APIs have become important features in modern JavaScript. We can use the fetch API to get the image resource and store it in memory, and then create a blob object for subsequent use. This approach not only provides better control over the loading process, but also captures potential errors.

Example 2: Preload using Promise and fetch API

async function preloadImagesWithFetch(imageUrls) {
  const promises = (async (url) =&gt; {
    try {
      const response = await fetch(url);
      if (!) {
        throw new Error(`Failed to load image from ${url}`);
      }
      const blob = await ();
      return (blob);
    } catch (error) {
      ();
    }
  });
  return (promises);
}

// Use examplepreloadImagesWithFetch(imageUrls).then(preloadedUrls =&gt; {
  ('All images preloaded:', preloadedUrls);
});

Method 3: Use IntersectionObserver API to combine lazy loading and preloading

The IntersectionObserver API allows us to listen to whether elements enter the viewport range, thus implementing Lazy Loading. However, we can also apply this mechanism in reverse, starting to preload related images before the elements are about to enter the viewport, achieving the effect of saving bandwidth and speeding up the display speed.

Example 3: Preloading in combination with IntersectionObserver API

function preloadImagesBeforeVisible(imageElements, threshold = 0.1) {
  const observer = new IntersectionObserver((entries, observer) =&gt; {
    (entry =&gt; {
      if ( ||  &gt; threshold) {
        const img = ;
        const src = ('data-src');
        if (src) {
           = src;
          ('data-src');
          (img); // Cancel observation        }
      }
    }, { threshold });
  });

  (img =&gt; {
    if (! &amp;&amp; ('data-src')) {
      (img);
    }
  });
}

// Use exampleconst imagesToPreload = ('img[data-src]');
preloadImagesBeforeVisible(imagesToPreload);

Method 4: Use link[rel="preload"] for declarative preloading

HTML5 introduces the <link rel="preload"> tag, which allows developers to inform browsers of which resources they need to load first in a declarative manner. This method is not only simple and intuitive, but also has good compatibility and is suitable for most modern browsers. By specifying the as attribute, we can explicitly tell the browser resource type so that it can be optimized appropriately.

Example 4: Preload using <link rel="preload">

<head>
  <link rel="preload" href="/" rel="external nofollow"  as="image">
  <link rel="preload" href="/" rel="external nofollow"  as="image">
  <link rel="preload" href="/" rel="external nofollow"  as="image">
</head>

Method 5: Use Service Worker to achieve offline preloading

Service Worker is a worker thread running in the background. It can intercept network requests and provide cache management functions. By configuring Service Worker, we can cache all image resources when the user first accesses, so that they can be displayed normally even if the network is disconnected. This is especially useful for mobile applications or PWAs (Progressive Web Apps).

Example 5: Use Service Worker for offline preloading

// 
('install', event =&gt; {
  (
    ('my-cache').then(cache =&gt; {
      return ([
        '/images/',
        '/images/',
        '/images/'
      ]);
    })
  );
});

('fetch', event =&gt; {
  (
    ().then(response =&gt; {
      return response || fetch();
    })
  );
});

// Register Service Workerif ('serviceWorker' in navigator) {
  ('load', () =&gt; {
    ('/')
      .then(registration =&gt; {
        ('Service Worker registered with scope:', );
      })
      .catch(error =&gt; {
        ('Service Worker registration failed:', error);
      });
  });
}

3. Function usage ideas and code examples from different angles

Improve the loading speed of the first screen

For home pages or other key pages, we can selectively preload some core images, such as logos, carousel pictures, etc. This not only speeds up the initial rendering of the page, but also allows users to feel the professionalism and high quality of the website.

Preloading example of home screen image

function preloadCriticalImages() {
  const criticalImages = [
    '/',
    '/'
  ];
  preloadImages(criticalImages);
}

// Called when the page is loading('DOMContentLoaded', preloadCriticalImages);

Enhanced user experience

In some cases, we may want to prepare the corresponding image resource before the user triggers a specific action. For example, when a pop-up window or toggle tab is opened, load up the upcoming image in advance to ensure seamless switching.

Operation trigger preload example

function preloadModalImages(modalId) {
  const modal = (modalId);
  const imageUrls = (('img')).map(img =&gt; );
  preloadImages(imageUrls);
}

//Bind event listener('.open-modal-button').addEventListener('click', () =&gt; {
  preloadModalImages('my-modal');
});

Optimize SEO performance

Search engine crawlers will also pay attention to the loading speed and quality of images. By rationally planning the image preloading strategy, we can improve the website's SEO score and attract more traffic. For example, add a key image for each pagerel="preload"Tags and make sure they can be loaded in a short time.

SEO Optimization Preload Example

<head>
  <link rel="preload" href="/" rel="external nofollow"  as="image">
  <link rel="preload" href="/" rel="external nofollow"  as="image">
</head>

Supports multiple devices

Considering the screen size and network conditions of different devices, we should flexibly adjust the image preloading strategy. For example, for mobile devices, a lower resolution image version can be selected, while for desktop devices, a higher-definition image can be loaded. In addition, it can also be determined whether to preload according to the user's network connection type (such as Wi-Fi, 4G, etc.).

Device adaptation preload example

function preloadImagesForDevice(imageUrls) {
  if ( &lt;= 768) {
    // mobile device    imageUrls = (url =&gt; (/\.jpg$/, '-'));
  } else {
    // Desktop equipment    imageUrls = (url =&gt; (/\.jpg$/, '-'));
  }
  preloadImages(imageUrls);
}

// Call according to device typepreloadImagesForDevice(imageUrls);

4. Usage skills and best practices in practical work development

As a web front-end developer, rational use of image preloading technology in daily work can significantly improve web page performance and user experience. Here are some suggestions and experience sharing:

  • Analyze the page structure: Carefully study the page layout and user behavior paths to determine which images must be preloaded and which can be delayed. For non-essential images, minimize the number of preloads to avoid excessive bandwidth consumption.
  • Consider network environment: Adjust the preloading strategy according to different network conditions. For example, preloaded content can be appropriately added in Wi-Fi environments, while caution should be maintained under cellular networks to avoid affecting users' normal use.
  • Monitor loading progress:usePromiseIntersectionObserverSimply use the API to track the load status of images in real time and deal with possible problems in a timely manner. If an image fails to load, you can try reloading or provide an alternative.
  • Optimize image format: Select the appropriate image format (such as WebP, JPEG 2000, etc.), and compress the file size as much as possible without affecting the visual effect. This not only speeds up loading, but also reduces the storage space usage.
  • Testing and debugging: Perform comprehensive testing on different devices and browsers to ensure that the preload logic is correct. You can use Chrome DevTools and other tools to view network requests and caches, find problems and improve them.
  • Combined with CDN acceleration: Host images on a content distribution network (CDN) and use its globally distributed nodes to shorten the time for resource acquisition. At the same time, ensure that the CDN is configured correctly and supports the latest protocols and technologies such as HTTP/2 and Brotli compression.
  • Follow official regulations: Write code strictly in accordance with the standards issued by W3C, WHATWG and other related organizations to ensure the compatibility and maintainability of the code. Pay attention to the latest HTML, CSS, and JavaScript specifications and update your knowledge system in a timely manner.

By deeply understanding the technical principles of image preloading and how it is implemented in JavaScript, you can write more intelligent, efficient and easy to maintain code. Mastering this knowledge will not only help you solve problems in actual development, but it can also add a technical strength to your career.

The above is the detailed summary of the method of JavaScript to implement image preloading. For more information about JavaScript image preloading, please pay attention to my other related articles!