如何在页面加载后执行 jquery 代码?

如果希望事件在您的 页面,您应该在 $(document) . ready ()函数。 里面的所有东西都会尽快装载 当加载 DOM 和 之前时 加载页面内容。

我想做的 javascript 代码只有 之后的页面内容是加载如何我可以做到这一点?

380305 次浏览

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

And if you want to run a second function after the first one finishes, see this stackoverflow answer.

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.
});
});

write the code that you want to be executed inside this. When your document is ready, this will be executed.

$(document).ready(function() {


});

I am looking for the same problem and here is what help me. Here is the jQuery version 3.1.0 and the load event is deprecated for use since jQuery version 1.8. The load event is removed from jQuery 3.0. Instead, you can use on method and bind the JavaScript load event:

$(window).on('load', function () {
alert("Window Loaded");
});

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.

nobody mentioned this

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

which is a shorthand function of

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

You can avoid get undefined in '$' this way

window.addEventListener("DOMContentLoaded", function(){
// Your code
});

EDIT: Using 'DOMContentLoaded' is faster than just 'load' because load wait page fully loaded, imgs included... while DomContentLoaded waits just the structure