开发者

preload images with a specific class with jquery

Is it possible to preload images that have a specific class applied to them?

for example - preload only images with class '.grid'

I've seen lots of examples of pr开发者_StackOverflow社区eload based on array, but my image names are dynamically generated (I'm using Drupal 6), and I don't want to preload the images globally unless I have to.

Any ideas? Thanks Stephanie


var imgs = new Array();
$('img.grid').each(function(idx){
 var i = new Image();
 i.src = $(this).attr('src');
 imgs.push(i);
});


If the problem you are trying to solve is to load images in your page that have the grid class faster, then there is no way to do that. To find the images in your page that have the grid class, you'd have to wait for the DOM to load and then search the DOM to find those images. At the point you are doing that, the browser is already working to load them. Nothing you can do in Javascript at that point can make the image load go any faster. The browser is already loading them.

The only thing I know that you could do is to make an array of the URLs that you want to load and you can preload those in the very first part of your javascript (script in the head tag) and this "might" get the images loading a little faster. But, in order to do this, you'd have to manually list out the images you want to apply this to. You can't wait for the page to load and look for them in the page because, by then, they're already being loaded as fast as they can be. If you control the server-side code, you could generate this list of images server-side and put that array into the JS. If you did that, it would look something like this:

<head>
<script type="text/javascript">
var preloadURLs = [
    "http://photos.smugmug.com/photos/344291068_HdnTo-Ti.jpg",
    "http://photos.smugmug.com/photos/344290837_ypsKL-Ti.jpg"
];

var preloadImgs = [], img;
for (var i = 0; i < preloadURLs.length; i++) {
    img = new Image();
    img.src = preloadURLs[i];
    preloadImgs.push(img);
}

</script>
</head>

In most browsers, this should serve to somewhat give priority to the loading of these images since their requests would be launched first before the page starts to load.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜