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
DDDOriginal
2024-12-28 17:48:14409browse

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;
    });
}

Usage:

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

jQuery Plugin Approach

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

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

Usage:

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

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!

Statement:
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