Home > Web Front-end > JS Tutorial > How Can I Efficiently Preload Images with jQuery?

How Can I Efficiently Preload Images with jQuery?

Mary-Kate Olsen
Release: 2024-12-18 00:20:10
Original
858 people have browsed it

How Can I Efficiently Preload Images with jQuery?

Preloading Images Efficiently with jQuery

If you're seeking a streamlined approach to preload images using JavaScript with jQuery, consider the following solutions:

Quick and Easy Method

For a lightweight and straightforward approach, try this function:

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively:
        // (new Image()).src = this;
    });
}
Copy after login

Usage:

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);
Copy after login

jQuery Plugin

If you prefer a plugin-based solution:

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}
Copy after login

Usage:

$(['img1.jpg','img2.jpg','img3.jpg']).preload();
Copy after login

These methods offer a quick, easy, and efficient way to preload images in jQuery.

The above is the detailed content of How Can I Efficiently Preload Images with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template