最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I hide a page contents until all the images are fully loaded? - Stack Overflow

programmeradmin1浏览0评论

I am trying to optimize a site which loads terribly. I already reordered, pressed and minified js and css, but the biggest problem are the images. This site has some really heavy images in it, so when it starts to load the content jumps while all the images are being loaded.

I cant manually set the height of the divs containing the images because they are user submitted, and although the width is a fixed value, height isn't.

I understand that this is probably not a good practice, but I think its better that the page takes two seconds before showing contents, that it being jumpy and unusable for those two seconds.

1.) Is this technically possible? How? (I would like to know this, even if its not a good practice)

2.) If this is not a good practice, how would you avoid this problem?

I am trying to optimize a site which loads terribly. I already reordered, pressed and minified js and css, but the biggest problem are the images. This site has some really heavy images in it, so when it starts to load the content jumps while all the images are being loaded.

I cant manually set the height of the divs containing the images because they are user submitted, and although the width is a fixed value, height isn't.

I understand that this is probably not a good practice, but I think its better that the page takes two seconds before showing contents, that it being jumpy and unusable for those two seconds.

1.) Is this technically possible? How? (I would like to know this, even if its not a good practice)

2.) If this is not a good practice, how would you avoid this problem?

Share Improve this question asked Aug 11, 2011 at 15:36 agente_secretoagente_secreto 8,07916 gold badges60 silver badges83 bronze badges 2
  • 1 Not really a best practice. Maybe try a pre-loader, or wait until all the images are loaded and then display them so that you have one jump instead of multiple. – ayyp Commented Aug 11, 2011 at 15:40
  • 1 Even if the images are user submitted, you should still know what the dimensions are on the server side. Make sure you set width and height on your img tags. When rendering the HTML for the image tag, use a function that reads images and gives you properties. You could cache the dimensions somewhere – Ruan Mendes Commented Aug 11, 2011 at 15:49
Add a ment  | 

5 Answers 5

Reset to default 2

It's extremely easy with JQuery. I'd remend using that framework anyway, even if it wasn't for this particular solution:

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
    });
}

Use it like this:

preload([
    'img/apple.jpg',
    'img/banana.jpg',
    'img/pear.jpg'
]);

Hiding your site at this point is easy with CSS and JQuery:

CSS:

body {
    display:none;
}

JQuery:

$(function(){
    $('body').show();
    // or fade it in: $('body').fadeIn();
});

Just after the Body tag, add a Div Element to cover the whole length and breadth of the page, make it white background or add a "Loading" image, set its z-index to Max (9999 or something) so its on top of everything, and give it some ID/Name

and Use a Javascript with Body onLoad Event to hide or remove that Div Element.

Something like

<body onload='document.body.removeChild(document.getElementById("bigDiv"));'>

<div style="width:100%;height:100%;background:white;" id=bigDiv>Loading...</div>

First important thing to check - make sure the images are cacheable. Sometimes caching of images is disabled. The way to check this is a direct call to the webserver:

 telnet localhost 8080
 GET /images/flibble.gif HTTP/1.0

And see what is returned. It should return something like Expires: or Cache-Control.

This page seems to describe it well: http://www.web-caching./mnot_tutorial/how.html

The other trick is to specify the size of the images in the tag. This vastly improves performance because the browser doesn't need to wait until the page is loaded.

I've written my own js image preloader before, what I'm about to post is pseudo-similar to it but will need some work. Basically in order to make your page load nicely, the answer isn't to hide the body to stop it jumping around, rather beautify what happens when the images do load. Besides throwing out the baby with the bath water, generally sites appear to the user to load faster if they can see something happening while they wait.

So what you need to do (for each image, or atleast each major or large image) is display a loading gif (check out http://ajaxload.info) while the image loads, then when it is finished you can use jQuery to animate it's container to the correct height and fade in the image. This stops your page jumping around (or rather makes it look prettier while it jumps).

To acheive this effect, something like this should do the trick:

function imageLoader(elem)
{
  //set all images in this elem to opacity 0
  elem.children('img').css('opacity', '0');
  var image = new Image();
  //show loading image
  elem.append('html for loading image');

  //when the image loads, animate the height of the elem and fade in image
  image.onload=function()
  { 
       var h = image.height;
       elem.animate({height:h+'px'}, function(){
         elem.children('img').fadeIn();
         elem.children('html for loading image').remove(); 
       });
  };

  image.src=elem.children('img').attr('src');
}

Use it like this:

imageLoader($('someElementWithAnImageTagInside'));

Again this is just psuedocode really but hopefully should give you some ideas.

Hope this helps

U can use block plugin to block the page. Link

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>