Home > Web Front-end > JS Tutorial > How to Preload Images in jQuery: A Quick and Easy Method vs. a Plugin Approach?

How to Preload Images in jQuery: A Quick and Easy Method vs. a Plugin Approach?

DDD
Release: 2024-12-28 17:48:14
Original
378 people have browsed it

How to Preload Images in jQuery: A Quick and Easy Method vs. a Plugin Approach?

Preloading Images with jQuery

Despite the availability of jQuery plugins, you may prefer a concise and lightweight solution for preloading images.

Quick and Easy Preloading

For a streamlined approach, consider the following code snippet:

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

Usage:

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

jQuery Plugin Approach

If you prefer a jQuery plugin, you can utilize the following:

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

Usage:

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

The above is the detailed content of How to Preload Images in jQuery: A Quick and Easy Method vs. a Plugin Approach?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template