Efficiently loading hidden/layered images in web page

左心房为你撑大大i 提交于 2019-12-11 08:15:09

问题


I have a layered div component which displays a successive series of large kb images by slide-animating away the top image to reveal the next image below. I'm trying to understand how best to approach this.

Approach 1:

layer a number of divs on top of each other, each with an image assigned as background, and slide away the divs as needed.

Will the hidden divs load their images on page load, or only when they are revealed? Is this browser/client specific behavior? Do all images (jpegs, pngs) behave the same way in this regard?

Approach 2:

Use only two divs- One that handles sliding, the other that will load and reveal the next image.

In this case, is it possible to pre-load the next image, so that the javascript isn't slowed down when the next image is revealed?

Thanks- and if anyone has other ideas, I'd love to hear them.


回答1:


Your first approach, even if the images are 'hidden' via CSS, will load all images by all browsers via HTTP requests. Your second approach or some variant of it is probably better.

I'd recommend using AJAX to pull down each image as you go. It's definitely possible to preload the images.

You may want to consider existing slideshow/lightbox type of plugins for jquery or javascript. It's been done so many times you will sort of be recreating the wheel (unless it's more of a learning experience thing)..

Here's an interesting example of preloading with callbacks to alert you when it's ready. Maybe a good one to adapt?

http://binarykitten.me.uk/dev/jq-plugins/107-jquery-image-preloader-plus-callbacks.html




回答2:


The first approach certainly degrades better. It will leave the images available and visible if viewed on a CSS-challenged browser. But that comes at the cost of having to pull down all the images from the get-go. The second approach is lighter on the initial hit, at the cost increased code complexity swapping images in/out.

You can definitely pre-load images with Javascript. just create an image object and set its source to whatever you want, which will automatically trigger downloading of the image. It doesn't have to be inserted into the DOM or visible to the user to do this.

Hidden divs SHOULD load their content automatically, whether they're visible or not. I can't think of any PC-based browsers that wouldn't do this, but I'd hazard a guess that some browsers intended for resource-limited devices (cell phones for one) might optimize things and delay loading contents until the container's made visible, to save on network traffic.



来源:https://stackoverflow.com/questions/3629506/efficiently-loading-hidden-layered-images-in-web-page

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