开发者

XHTML JavaScript preload images before rest of page is loaded

开发者 https://www.devze.com 2023-01-18 01:38 出处:网络
Is there anyway I can delay the display of the HTML code (page) untilsome certain images are loaded so that the layout appears开发者_如何学编程 with the header images as well as the HTML?

Is there anyway I can delay the display of the HTML code (page) until some certain images are loaded so that the layout appears开发者_如何学编程 with the header images as well as the HTML?

Thank you.


This should do it, but it's your responsibility to protect the clients from themselves - after all, you're the professional...

<head>
 <script type="text/javascript">
//<![CDATA[
with (document.documentElement.style) {

  visibility = 'hidden';
  overflow = 'hidden';

  window.onload = function() {
    visibility = '';
    overflow = '';
  };
}​
//]]>
 </script>
</head>

note: using display = 'none' instead doesn't work in my (somewhat old) Opera 10.10 as the onload will fire immediately...

Also, this will delay displaying the page until all external resources have been loaded. If you only want to wait for certain images, you'll need a more sophisticated script (untested):

  <head>
  <script type="text/javascript">
//<![CDATA[
document.documentElement.style.display = 'none';
//]]>
  </script>
 </head>
 <body>
  <img stc="…" width="…" height="…" alt="…" class="preload">
  <!-- page contents… -->
  <script type="text/javascript">
//<![CDATA[
(function() {
    var remaining = 0;

    function listener() {
        if(!--remaining)
            document.documentElement.style.display = '';
    }

    for(var i = 0; i < document.images.length; ++i) {
        var img = document.images[i];
        if(/(^|\s)preload(\s|$)/.test(img.className) && !img.complete) {
            ++remaining;
            img.onload = listener;
            img.onerror = listener;
        }
    }
})();
//]]>
  </script>
 </body>


I share Christoph's opinion, that a page should be shown to the user as fast as possible--even just parts of the page. It is annoying if nothing seems to happens.

But you can try

<body id='body' style='display:none;' 
      onload="document.getElementById('body').style.display='block';">

( or does also work

<body style='display:none;' onload="this.style.display='block';">

? -- need to try)

That would display the page after all images, scripts, stylesheets, and multimedia files are loaded.

0

精彩评论

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

关注公众号