Sometimes you may need to preload images on your website or pages dynamically. In this article, we will learn how to preload images with jQuery.
How to Preload Images with jQuery
Here is a simple jQuery function to make python dictionary from two lists.
function preload(arrayOfImages) { $(arrayOfImages).each(function(){ $('<img/>')[0].src = this; }); }
You can call the above function as shown below.
preload([ 'img/image1.jpg', 'img/image2.jpg', 'img/image3.jpg' ]);
Let us look at the above function in detail. We basically pass an array of image paths to our preload() function. We iterate through each array item and create an img tag DOM element on our page. For each img tag, we use the current iteration’s array item value (image path) as source. That’s it. In addition to setting .src attribute of each image, you can also set other attributes as per your requirement.
You can also create a jQuery plugin out of the above function, if you want, as shown below.
$.fn.preload = function() { this.each(function(){ $('<img/>')[0].src = this; }); } // Usage: $(['img1.jpg','img2.jpg','img3.jpg']).preload();
In this article, we have learnt how to preload images using jQuery. It is very useful if you want to load images in an image gallery or infinite scroll UI, which you hide initially, but display as per your requirement.
Of course, there are many jQuery plugins for this purpose. We have learnt how to do this using plain jQuery.
Also read:
How to Make Python Dictionary From Two Lists
How to Check if JavaScript Object Property is Undefined
How to Get Difference Between Two Dates in JavaScript
How to Shuffle Array in JavaScript
How to Dynamically Create Python Variables
Related posts:
How to Detect Invalid Date in JavaScript
How to Add 30 Minutes to JS Date Object
How to Check if Variable is Object in JS
How to Get Class List for DOM Element
How to Return Response from Asynchronous Call in JavaScript
How to Prevent Web Page from Being Loaded in Iframe
How to Add Event to Dynamic Elements in JavaScript
How to Find DOM Element Using Attribute Value

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.