How to do jquery code AFTER page loading?
If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
I want to do javascript code only after the page contents are loaded how can I do that?
Use load
instead of ready
:
$(document).load(function () {
// code here
});
Update
You need to use .on()
since jQuery 1.8. (http://api.jquery.com/on/)
$(window).on('load', function() {
// code here
});
From this answer:
According to http://blog.jquery.com/2016/06/09/jquery-3-0-final-released/:
Removed deprecated event aliases
.load
,.unload
, and.error
, deprecated since jQuery 1.8, are no more. Use.on()
to register listeners.https://github.com/jquery/jquery/issues/2286
Following
$(document).ready(function() {
});
can be replaced
$(window).bind("load", function() {
// insert your code here
});
There is one more way which I'm using to increase the page load time.
$(document).ready(function() {
$(window).load(function() {
//insert all your ajax callback code here.
//Which will run only after page is fully loaded in background.
});
});
nobody mentioned this
$(function() {
// place your code
});
which is a shorthand function of
$(document).ready(function() { .. });
Edit: This code will wait until all content (images and scripts) are fully loaded and rendered in the browser.
I've had this problem where $(window).on('load',function(){ ... })
would fire too quick for my code since the Javascript I used was for formatting purposes and hiding elements. The elements where hidden too soon and where left with a height of 0.
I now use $(window).on('pageshow',function(){ //code here });
and it fires at the time I need.