Reputation: 33654
I have the following code:
var products = [];
$('.mCSB_container').children('li').each(function () {
products.push($(this).data("full-image"));
});
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
$(products).preload();
what does this preload function does? Does it iterate through the array of products and then set the src to this? But what is this in this case.. What's an equivalent of this function without using the $.fn
Upvotes: 0
Views: 532
Reputation: 42736
Without using the preload
function you can do:
products.forEach(function(src) {
var img = document.createElement("img");
img.src = src;
});
using $.fn
is just a way of adding to the functions that are available to objects created by the jQuery function/object
Upvotes: 1
Reputation: 707426
$(products).preload();
calls the preload method for each item in the $(products)
jQuery object. It sets the .src
attribute of the a newly created image object in the page to each string in the products
array. I would guess that it's an attempt to cause the browser to preload images before they are needed for other uses.
You may find it simpler and clearer to use a preload function as described in this post: How do you cache an image in Javascript.
If .preload()
is not called, then the images will take time to load when they are needed later in the page or later in the javascript. The purpose of preloading is to get the images into the browser's cache so they don't have to be loaded over the internet when they are next needed.
The assignment $.fn.preload = function() {...}
is just defining the .preload()
method as a method on all future jQuery objects. In jQuery fn
is like assinging to the .prototype
of jQuery objects.
Upvotes: 2