Only load the background-image when it has been fully loaded?

background, html, javascript, jquery

Solution

If the image is included with an `img` element:

<img src="bg.jpg" id="img" onload="this.style.opacity='1'">

<script>
    document.getElementById("img").style.opacity="0";
</script>

That should load the image normally if JavaScript is disabled, but show it only once it loads assuming it's enabled.

One thing to note (that I overlooked): some browsers will not even attempt to load an image if its `display` property is `none`. That's why this method uses the `opacity` attribute.

Problem

Well, the title pretty much describes my question: How to load the background-image dynamically after it has been fully loaded? Sometimes, I must use backgrounds that are so big that it can take a while for the browser to download it. I'd rather 'load it in the background' and let it fade in when it has been fully loaded. I think jQuery would be best to be using, but I also want my background to appear if JavaScript has been disabled. If this really isn't possible, so be it, but I think it is? Best regards, Aart ........ EDIT: Thanks a bunch, guys! I've been bugged with this for ages and just couldn't think of a nice and easy way. I converted Jeffrey's Javascript-solution into a jQuery one, just because jQuery's built-in fade looks so awesome. I'll just post it here in case anyone else has the same issue: ``` <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script> <script type='text/javascript'> $(document).ready(function() { $('#img').css('opacity','0').load(function() { $(this).animate({ opacity: 1 }, 500); }); }); </script> <img src='yourimage.jpg' id='img'/> ```

Original source