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 Set/Unset Cookie With jQuery
How to Detect Scroll Direction in JavaScript
How to Change Element's Class in JavaScript
JavaScript Round to 2 Decimal Places
Return False vs PreventDefault in JavaScript
How to Find Max Value of Attribute in Array of JS Objects
How to Get Previous URL in JavaScript
How to Convert UTC Date Time to Local Date Time in JS

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