Jquery - if page loaded

Is there any trick how to start a function in javascript, which starts when the page is completely loaded?

Answers


If you mean when the HTML document has loaded, use the ready event:

$(document).ready(function(){
  ...
});

Or the shorthand:

$(function(){
  ...
});

If you mean when the page including all style sheets, scripts, images and whatnot has completed loading, use the load event:

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

$( window ).bind( 'load', function()
{
    //your code in here
} );

Check this: http://api.jquery.com/ready/

 jQuery(document).ready(function($) {
 // Code using $ as usual goes here.
 });

This depends on your definition of "load". Check out these two functions in the jQuery docs:

Specifically, you can see the differences in the ready() function's doc page.

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.


When DOM is ready then use .ready event.

jQuery(document).ready(function(){
  //content
});

you also use .load event when page load images.

jQuery(window).load(function(){
  //content
});

Try binding a load event callback to the last image on the page.


To call a method once the document is loaded completely use

$(document).ready(function(){
  ...
});

Or else if page is loading through an ajax call use

$('#containerdiv').load('samplepage.jsp', function() {
  alert("ajax load complet.."); 
});

If you really want your Javascript to run once 'everything' all your HTML is loaded, you can with

window.onload = function(){
   // Do stuff
}

You are looking for the window load event.

In jQuery you attach the load event as follows:

$(document).ready(function() {

  $(window).load(function() {

  }

}

Note that you need to place this inside a document ready for some browsers, IE8 OTTOMH.


Need Your Help

Why does ofstream insert a 0x0D byte before 0x0A?

c++ ofstream

I'm outputing an array of unsigned characters in C++ using ofstream fout("filename");

How do I get "rainbow parentheses" in emacs?

emacs clojure syntax-highlighting

I would like rainbow parens for editing Clojure in Emacs and since VI does this I assume that in Emacs it should be something like M-x butterfly or something :)