是更好地使用"隐藏" CSS属性或取每组的新形象? [英] Is it better to use the "hidden" CSS attribute or fetch each set of new images?

查看:115
本文介绍了是更好地使用"隐藏" CSS属性或取每组的新形象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过jQ​​uery的AJAX调用使用JSONP获取一群来自Flickr的照片数据。我想在一个时间显示的 N 的图像,那么每个用户点击一个按钮时显示下的 N 的图像。

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.

我读过的一个办法是将所有的图像添加到DOM中的回调函数,并使用隐藏的CSS属性为隐藏和显示下一个的 N 的图像,用户点击。这是一个推荐的做法呢?

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?

推荐答案

这完全取决于你想要做的事。如果创建 IMG 元素,并设置其的src ,即便是通过隐藏显示:无(对于这个问题,即使你不将它们添加到DOM的话),浏览器仍然会从服务器请求的图像。如果页面允许用户观看他们之前,通过图像进行筛选,或允许分页,能够产生不必要的网络流量。理想情况下,prefetch图像,只有当它是相当有可能的用户将看到他们 —但足够早,用户不剩等待他们。

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.

需要注意的是,同样,你的的必须把 IMG 元素在DOM,直到你准备好。只要创建 IMG 元素,并设置其的src 就足够了(的试试这里,即code从不添加 IMG 的DOM的话)。所以,你可以保留的 IMG 元素的地图,例如:

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;
    }
}

然后你让他们当你准备好了他们,但无需地方掖他们离开了DOM。

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

这篇关于是更好地使用"隐藏" CSS属性或取每组的新形象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆