Home > Article > Web Front-end > Three major methods to achieve image preloading and analysis of their advantages and disadvantages_javascript skills
Preloading images is a great way to improve user experience. With images pre-loaded into the browser, visitors can smoothly surf your site and enjoy blazingly fast loading times. This is very beneficial for image galleries and websites where images take up a large proportion. It ensures that images are published quickly and seamlessly, and it also helps users get a better user experience when browsing your website content. This article will share three different preloading techniques to enhance website performance and usability.
Method 1: Use CSS and JavaScript to implement preloading
There are many ways to implement preloaded images, including using CSS, JavaScript, and various combinations of the two. These technologies can design corresponding solutions according to different design scenarios and are very efficient.
Simply using CSS, you can preload images easily and efficiently. The code is as follows:
Applying these three ID selectors to the (X)HTML element, we can preload the image onto the off-screen background through the CSS background attribute. As long as the paths to these images remain the same, the browser will use the preloaded (cached) images during the rendering process when they are called elsewhere on the web page. Simple, efficient and doesn't require any JavaScript.
Although this method is efficient, there is still room for improvement. Images loaded using this method will be loaded together with other content on the page, increasing the overall loading time of the page. To solve this problem, we added some JavaScript code to delay the preloading time until the page is loaded. The code is as follows:
In the first part of the script, we get the element using the class selector and set the background attribute on it to preload different images.
In the second part of the script, we use the addLoadEvent() function to delay the loading time of the preloader() function until the page is loaded.
What happens if JavaScript doesn't run properly in the user's browser? It's very simple. The image will not be preloaded. When the page calls the image, it will be displayed normally.
Method 2: Use JavaScript only to implement preloading
The above method is sometimes very efficient, but we gradually found that it would consume too much time in the actual implementation process. Instead, I prefer to use pure JavaScript for image preloading. Below are two such preloading methods that work beautifully on all modern browsers.
JavaScript snippet 1
Just simply edit and load the path and name of the required image, it’s easy to implement: