Reputation: 125
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.
Upvotes: 3
Views: 13783
Reputation: 151
Use link to preload items like images, videos and other content before the webpage will be shown. It works with many types of content. More about it in https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
<link rel="preload" href="img.png" as="image">
Upvotes: 6
Reputation: 774
You can put
<img style="display:none;" src="../images/background.jpg" />
at the top of your <body>
tag to make load it earlier.
Upvotes: 1
Reputation: 41605
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.
Upvotes: 7