4

I have a simple HTML page with a little JavaScript in it. The JavaScript launches onLoad in the body. The body also has a background image. The JavaScript launches before the background image is loaded. Is there a way to have the body onLoad wait for the body background image to load?

<body background="http://xxx.com/xxx.jpeg" id="myBody" onload="pageLoaded()">
jcmitch
  • 2,088
  • 9
  • 27
  • 33
  • 1
    Use window.onload in place of body.onload, as mentioned here: http://stackoverflow.com/questions/1033398/execute-javascript-when-page-has-fully-loaded – Mike Guthrie Mar 02 '12 at 18:26

4 Answers4

5

If you want to make sure a script launches after all the images have been loaded, then use

$(window).load(function() {
//.......................
});

This event, will only fire once all the scripts, css, js, images have been load, unlike $(document).ready();

Starx
  • 77,474
  • 47
  • 185
  • 261
2

You can try with

jQuery(window).load(function() {
     //your code here
});

jQuery(document).ready(function() {
     //your code here
 });

But i don't think whether it will consider background image loading. A more efficient way will be to use this jQuery plugin:

https://github.com/alexanderdickson/waitForImages

You can make the jQuery function call like :

jQuery('body').waitForImages(function() {
    //your code here
});

Hope this helps you :)

Sabari
  • 6,205
  • 1
  • 27
  • 36
  • You need to enable the `waitForAll` option for the plugin to consider background images. – alex Mar 15 '12 at 11:28
1

did you try with JQuery? http://api.jquery.com/ready/

<script>
$(document).ready(pageLoaded)
</script>
Francois
  • 10,730
  • 7
  • 47
  • 80
  • I think you want `$(document).load(pageLoaded);` http://api.jquery.com/load-event/. This attaches a function to the event that occurs when images and other elements on the page have loaded. – dangerChihuahua007 Mar 02 '12 at 18:27
1

Or listen for DOM ready without jQuery

tkone
  • 22,092
  • 5
  • 54
  • 78