简体   繁体   中英

How can I make sure a background image displays before the page loads?

Is there a way to make sure a (large, 300K) background picture is always displayed first BEFORE any other content is shown on the page?

On the server we have access to PHP.

All the html content is served and parsed before it even starts to fetch the image, so you have a problem before you start.

You could circumvent this by programmatically hiding the content, and then triggering a "show" of it when the image is loaded.

ie:

<html>
  <body>
    <image here/>
    <div id="content" style="display:none;" >

    </div>
    <script type="psudocode"> 
     when(image.loaded){ 
          $("#content").show();
     }
    </script>
  </body>
</html>

If you have all content inside a container, you can probably come pretty close using this techique. It will also fail gracefully if javascript is disabled/unavailable.

So if you have to do this because of a manager or something, this is the method I would use.

<html><head><!-- head section --></head>
<body>
    <div id="container">
       <script type="text/javascript">
       <!--
         document.getElementById('container').style.display = 'none';
       -->
       </script>
       Content goes here
    </div>
    <script type="text/javascript">
    <!--
      document.getElementById('container').style.display = 'block';
    -->
    </script>
</body></html>

If you have very little content, however, it probably won't do much good. You could of course add a timer on the second javascript block, to delay it for a second or so :P

<html><head>
<script type="text/javascript">
//Hide on load
onload=function(){
    document.body.style.display="none";
    var imag = new Image();

    imag.onload=function(){
        var main = document.body;
        main.style.backgroundImage="url("+this.src+")";
        main.style.display="";

    };
    imag.src="http://dayton.hq.nasa.gov/IMAGES/MEDIUM/GPN-2000-001935.jpg";
}
</script>
</head>
<body>
    YOU CAN' T SEE MEE!!
</body>
</html>

A possible way, if you don't want to rely on JavaScript, is to make a dummy page with only the background image. After a few seconds, it redirects to the real page, and the background will load quickly because it is already in cache.

Not a super attractive solution, if the timing is fixed, I reckon.
Note that 300KB is quite big for a background image. I have seen worse, somebody using a 1MB image: even with a relatively fast connexion, I could see the background load way after the elements of the page.

我认为您唯一能够做到这一点的方法就是使用javascript-向用户HTML发送仅包含背景图片和一些javascript的javascript,这些javascript需要等待一段时间才能显示其余内容,或者使用AJAX来检索其余内容(基本上是同一件事)。

您可以将页面内的图像作为base64图像加载,然后该图像将随页面一起加载。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM