Please check out the new Help Developer forum

Show Sidebar

Loading the background image first

September 3, 2008

When loading images on a website the background image could be the last to load which doesn’t look too professional. In this very short tutorial (more a tip I suppose) I will show you how to load the background image before anything else, you can apply this to any image that you wish, it is achieved by a bit of javascript in the head section.
Continues below...



In between the <head> and </head> tags of your html file, add the script tags:


<script type="text/javascript">

</script>

It is worth mentioning that this wont work in browsers without javascript enabled, but the majority do so there shouldn’t be any real problems. If a browser doesn’t have javascript then it will continue to load as normal.

Now add the following code in between the script tags like this:


<script type="text/javascript">
ImageA = new Image(width,height)
ImageA.src = "URL of Image"
</script>

Replace the (width,height) with the dimensions of your image, eg (100,100) and the “URL of Image” to the URL of the image eg “http://help-developer.com/image.jpg”. Now it should load before all other images on the page.

To add more than one image you can do something like this:


<script type="text/javascript">

ImageA = new Image(100,100)
ImageA.src = "http://help-developer.com/imageA.jpg"

ImageB = new Image(100,100)
ImageB.src = "http://help-developer.com/imageB.jpg" </script>

ImageC = new Image(100,100)
ImageC.src = "http://help-developer.com/imageC.jpg" </script>

There you have it, how to load an image first, this works because javascript (and the content between the <head> and </head> tags) is loaded in the browser before the content, hence before any other images or CSS styles.

Submit to Stumbleupon Submit to Del.icio.us Submit to Google

SUBSCRIBE TO RSS

RSS FEED - EMAIL FEED

Comments RSS Feed

5 Comments

Comments Trackbacks
  1. Jason Says:

    Brilliant tutorial mate, seriously when ever my those heavy bg background images takes to much time to load and even in the end after all the design elements get loaded it appears, that really makes the whole look a bit more spoiled.


  2. simon

    simon Says:

    works great in firefox and ie, but it doesn’t seem to work in safari? do you know what needs changing so it does?

  3. Simon North Says:

    Safari occasionally has problems with things like this, as a web designer I wish there was just one browser but that aint gonna happen :(

    Maybe setting it up as a function like here may help: http://articles.techrepublic.com.com/5100-10878_11-5214317.html and calling it in the body tag

    Let me know how it goes

  4. Simon North Says:

    @Jason

    I know what you mean its awful when that happens.



Leave a Reply