How to load a small css background image before lo

2019-04-17 07:37发布

I'm wondering if you can help. I have a small image (46kb) which is currently called in CSS like this:

html {
background: #000 url(../images/background.jpg) repeat fixed;
}

The problem I have with this at the moment is that the background is the last thing to load. On most of my pages I have anywhere from around 50 to 150 small 4kb images (which are content images). Consequently all these images load first before the background image. While this isn't a big deal, as the content is still readable, surely there is a way to load the small background image first?

Ideally I would like to use a CSS solution, but JS is fine, but don't want to use Jquery. I have tried a few methods, but quite a few of these require the image to be placed in the HTML, which is not possible in this case.

Thanks.

Edit: Just to clarify about JQuery, I haven't used it at all in the site so far, so it seems a bit overkill to use it just for loading a small background image. And yes the html {} declaration is at the top of the CSS file (just below some resetting declarations.

1条回答
时光不老,我们不散
2楼-- · 2019-04-17 08:01

Backgrounds are usually loaded at the end.

You could try to preload them by using:

body:after{
    display:none;
    content: url(img01.png) url(img02.png) url(img03.png);
}

Or by using javascript:

<script>
    var img1 = new Image();
    var img2 = new Image();
    var img3 = new Image();
    img1.src="img01.png";
    img2.src="img02.png";
    img3.src="img03.png";
</script>

Or you could also delay the loading of the normal images by using jQuery and do something like:

<script type="text/javascript">
$(document).ready(function() {
    $("#img1").attr("src", "img01.png");
    $("#img2").attr("src", "img02.png");
    $("#img3").attr("src", "img03.png");
});
</script>

And of course, the javascript code should be in the header of the site. Not at the bottom before the </body> tag as it is usually placed.

查看更多
登录 后发表回答