Is it better to use the “hidden” CSS attribute or fetch each set of new images?

淺唱寂寞╮ 提交于 2019-12-11 03:54:22

问题


I'm trying to fetch a bunch of photo data from Flickr via a jQuery AJAX call using JSONP. I'd like to display n images at a time, then show the next n images each time the user clicks a button.

I've read that one way is to add all the images to the DOM in the callback function and use the "hidden" CSS attribute to hide and reveal the next n images as the user clicks. Is this a recommended practice?


回答1:


It depends entirely on what you're trying to do. If you create img elements and set their src, even if they're hidden via display: none (for that matter, even if you don't add them to the DOM at all) the browser will still request the image from the server. If your page allows the user to filter through the images before viewing them, or allows paging, that can generate unnecessary network traffic. Ideally, prefetch images only when it's fairly likely the user will view them — but early enough that the user isn't left waiting for them.

Note that, again, you don't have to put the img elements in the DOM until you're ready to. Just creating the img element and setting its src is sufficient (try it here, that code never adds the img to the DOM at all). So you could keep a map of the img elements, for instance:

var preloaded = {};
function preload(path) {
    var img;
    if (!preloaded[path]) {
        preloaded[path] = img = document.createElement('img');
        img.src = path;
    }
}

Then you have them when you're ready for them, but without having to tuck them away somewhere in the DOM.




回答2:


Yes, it is best to load all the images as early as possible. This decreases wait time for the user, and they are more likely to view all your content.

You should load the first n images, then on the call back load the next n (hidden of course), and then on their call back so on and so forth until everything is pre-loaded.

That being said, if you have 100s of sets of size n, you should limit the number of pre-loading, maybe only preload the next two or three sets (and every click further should load another set). The idea is to always be ahead of the user so they never have to wait to view the next set of images.




回答3:


it is better achieved by carousel. There was a example of flickr carousel. Check the below link it may be useful for http://sorgalla.com/projects/jcarousel/examples/dynamic_flickr_feed.htmlou.



来源:https://stackoverflow.com/questions/8353733/is-it-better-to-use-the-hidden-css-attribute-or-fetch-each-set-of-new-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!