Home >Web Front-end >JS Tutorial >How Can I Quickly Preload Images Using jQuery?
Preloading Images with jQuery: A Quick and Easy Guide
While complex image preloading scripts are available, this article provides a concise and straightforward method of preloading images using jQuery.
The jQuery Code
The following snippet demonstrates a simple and efficient way to preload multiple images:
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' ]);
In this code, the preload() function takes an array of image paths and preloads each image by creating an invisible element and setting its src attribute to the image path. Alternatively, you can also use (new Image()).src = this to preload images.
An Alternative jQuery Plugin
If a plugin approach is preferred, the following code snippet provides a concise plugin:
$.fn.preload = function() { this.each(function(){ $('<img/>')[0].src = this; }); } // Usage: $(['img1.jpg','img2.jpg','img3.jpg']).preload();
This plugin extends the jQuery object and allows you to preload images by calling the preload() method on an array of image paths.
With these methods, preloading images becomes a quick and effortless task, ensuring optimal performance for your web application.
The above is the detailed content of How Can I Quickly Preload Images Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!