2

I want a way to know if a particular web page is completely loaded using javascript

Ex) A web page can have dynamic contents getting displayed through Ajax, or contents comming through javascript, all the images and css.I need to find out when all these contents are loaded properly and the webpage is stablilized.

I got some pointers like ondocumentready its an alternate soultion for window.onload, onreadystatechange but these solutions are unreliable sometimes it works and sometimes it doesn’t

Also the solution should be browser independent, i.e it should work for all browsers

Any pointers on this will be highly appreciated

Thanks in advance

user105165
  • 93
  • 1
  • 8

4 Answers4

4

Use jQuery and its easy:

<script type="text/javascript">
    $(document).ready(function() {
        alert('doc is ready');
        });
    });
</script>
  • browser independent
  • highly reliable
  • awesome
Matt Kocaj
  • 11,278
  • 6
  • 51
  • 79
1

You can also use the following. It's a shorthand version of the code posted by @cottsak

$(function() 
{ 
     // your code 
});

if you’re using jQuery.noConflict() (which is used to give control of the $ variable back to whichever library first implemented it), you can do this:

By adding jQuery.noConflict(), jquery won't conflict with $ variables of other libraries

jQuery(function($) 
{ 
       // your code
});
rahul
  • 184,426
  • 49
  • 232
  • 263
1

Using pure javascript you can put javascript in the onload event of the body tag like so:

<body onload="function">

This will trigger when the page has finished loading.

Rigobert Song
  • 2,766
  • 2
  • 30
  • 47
  • No, this is not recommended as it's not very reliable in comparison to jQuerys method described above. – Niklas Wulff Oct 19 '11 at 10:53
  • what if I don't want to use jQuery? – Rigobert Song Oct 19 '11 at 13:39
  • Hmm, I reread the question now and realise I may have gotten the poster wrong... The ´body onload´ event is designed to wait for resources, which is what the poster wanted. I always use jQuery for stability and cross browser ability, but maybe onload would perform better in this case. Will retract my vote and keep watching the thread. – Niklas Wulff Oct 19 '11 at 14:52
0

As a comparison of both answers by @Rigobert and @cottsack:

window.onload:

should be used only to detect a fully-loaded page.

So it should be a good fit for your question.

Whereas $(document).ready( fires (in most cases, browser-dependent)

when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

See also window-onload-vs-document-ready and the DOMContentLoaded event (which seemingly triggers JQuery's $(document).ready()). jquery-ready-vs-window-onload has a nice answer, too.

Community
  • 1
  • 1
serv-inc
  • 35,772
  • 9
  • 166
  • 188