Preloading images with jQuery

Let's understand what does preloading an image means and how can it be achieved using jQuery?
Submitted by Pratishtha Saxena, on September 07, 2022

Prerequisite: Adding jQuery to Your Web Pages

Preloading Images

When a webpage loads, it has to make sure that all the elements load on time – the images, the videos, the audio, etc. Since these things take a little more time than usual to load completely, it may decrease the websites' loading time. Hence it will result in fewer users visiting the site. These small things have to be perfect to increase the productivity of the website.

Thus, preloading the elements is the solution for it. Let's consider images only for some time. Preloading anything means that the element has already been loaded at the backend once, and now when the page loads and shows on the screen, these preloaded elements are fetched from the backend at that time. This way it does not takes a lot of time to load on the page. Hence it is more user-friendly.

jQuery attr() Method

This complete task may sound a bit complicated but rather it is a very simple job to do. As we know the attr() method of jQuery does a lot of things and is one of the most used methods, preloading of images can also be performed with its help.

Using the attr() method, the source of the image is stored beforehand in a variable. This variable can be called whenever and wherever it is needed. This way, the image is loaded only once and called out many times, making the loading of various images comparatively lesser.

Syntax:

$(selector).attr(attribute, value);

In place of the selector, the id name or the element name of the image tag can be mentioned. The attribute will take src and in value, we need to give the location of the image.

Let's see the below-mentioned jQuery example.

Example to Preload Images with jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Preloading Image Using jQuery</h2>
    <div></div>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function() {
        var img = $('<img>').attr("src", "https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=")
        $('div').html(img);
    });
  </script>
</html>

Output:

Example: Preloading images with jQuery






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.