开发者

With JS, is it possible to block the loading of images that are statically defined in the HTML?

开发者 https://www.devze.com 2023-03-14 22:40 出处:网络
So I have a hand-coded one-pager site with a very long length and dozens of images. Let\'s skip the discussion on whether that\'s a great strategy, but the situation is is that rendering all these ima

So I have a hand-coded one-pager site with a very long length and dozens of images. Let's skip the discussion on whether that's a great strategy, but the situation is is that rendering all these images as fast as can be can slow down the user experience, especially if he tries to scroll or interact with the page before all of the heavy image assets have been loade开发者_运维知识库d.

Ideally, I'd want to delay the loading of assets until the user is on top of the section in which the images are loaded, or very near it.

So, if everything is already in there statically, i.e.:

<img src="images/photo.jpg" alt="Photo" />

Is it possible, and always successful, to do something like:

$(document).ready(function(){
  $("img").each(function(){
        $(this).attr("data-src", $(this).attr('src'));
        $(this).attr("src", ''); 
  })
})

IIRC, simply hiding all the img elements with css by setting display to none won't stop them from loading in the background. And I wasn't sure if the document.ready callback would execute before any of the assets were rendered.

Or should I just say, screw JS-disabled clients and load in assets using ajax and json?


document.ready is after everything is in DOM. Images are loaded before, if I know.

Why can't you do it like this?

<img data-src="yourimage.png" class="img_i_need" />

and if you need it, use

$(function() {
    $("div").click(function() {
        $(".img_i_need").each(function() {
            $(this).attr('src', $(this).attr('data-src'));
        });
    });
});

http://jsfiddle.net/genesis/nDq82/3/


Never screw JS-disabled clients, for any reason.

That said, your idea is what I've also thought reading your question. Dunno if it works though.

0

精彩评论

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