在完成页面加载后调用函数

时间:2022-11-05 23:06:00

I am using following code to execute some statements after page load.

我正在使用下面的代码在页面加载之后执行一些语句。

 <script type="text/javascript">
    window.onload = function () { 

        newInvite();
        document.ag.src="b.jpg";
    }
</script>

But this code does not work properly. The function is called even if some images or elements are loading. What I want is to call the function the the page is loaded completely.

但是这个代码不能正常工作。即使某些图像或元素正在加载,函数也会被调用。我想要的是调用这个函数页面被完全加载。

14 个解决方案

#1


112  

this may work for you :

这可能对你有用:

document.addEventListener('DOMContentLoaded', function() {
   // your code here
}, false);

or if your comfort with jquery,

或者如果你喜欢jquery,

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

$(document).ready() fires on DOMContentLoaded, but this event is not being fired consistently among browsers. This is why jQuery will most probably implement some heavy workarounds to support all the browsers. And this will make it very difficult to "exactly" simulate the behavior using plain Javascript (but not impossible of course).

$(document).ready()在DOMContentLoaded后触发,但是在浏览器之间并没有持续地触发这个事件。这就是为什么jQuery很可能会实现一些繁重的工作区来支持所有的浏览器。这将使“精确”模拟使用普通Javascript的行为变得非常困难(当然也不是不可能)。

as Jeffrey Sweeney and J Torres suggested, i think its better to have a setTimeout function, before firing the function like below :

正如Jeffrey Sweeney和J Torres所建议的,我认为最好先有一个setTimeout函数,然后再触发如下函数:

setTimeout(function(){
 //your code here
}, 3000);

#2


27  

If you can use jQuery, look at load. You could then set your function to run after your element finishes loading.

如果可以使用jQuery,请查看load。然后可以将函数设置为在元素加载完成后运行。

For example, consider a page with a simple image:

例如,考虑一个具有简单图像的页面:

<img src="book.png" alt="Book" id="book" />

The event handler can be bound to the image:

事件处理程序可以绑定到图像:

$('#book').load(function() {
  // Handler for .load() called.
});

If you need all elements on the current window to load, you can use

如果需要加载当前窗口中的所有元素,可以使用

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

#3


14  

jQuery has excellent shorthand:

jQuery具有良好的速记法:

$(function(){

   // here code anything you want to run after page load

});

The below code is NO LONGER recommended!

document.onreadystatechange = function(){
   if(document.readyState === 'complete'){
      ............................
   }
}

because changes document property globally, instead of attaching a function to load event. So, DONT USE THAT.

因为它改变了全局的文档属性,而不是附加一个函数来加载事件。所以,不要使用。

#4


12  

I'm little bit confuse that what you means by page load completed, "DOM Load" or "Content Load" as well? In a html page load can fire event after two type event.

我有点搞不懂你所说的页面加载完成,“DOM load”或者“Content load”是什么意思?在html页面中,加载可以在两个类型事件之后触发事件。

  1. DOM load: Which ensure the entire DOM tree loaded start to end. But not ensure load the reference content. Suppose you added images by the img tags, so this event ensure that all the img loaded but no the images properly loaded or not. To get this event you should write following way:

    DOM load:确保加载的整个DOM树开始结束。但不能确保加载引用内容。假设您通过img标记添加了图像,因此此事件确保所有img都已加载,但没有正确加载图像。要得到这个事件,你应该这样写:

    document.addEventListener('DOMContentLoaded', function() {
       // your code here
    }, false);
    

    Or using jQuery:

    或使用jQuery:

    $(document).ready(function(){
    // your code
    });
    
  2. After DOM and Content Load: Which indicate the the DOM and Content load as well. It will ensure not only img tag it will ensure also all images or other relative content loaded. To get this event you should write following way:

    在DOM和Content Load之后:这也表示DOM和Content Load。它不仅能保证img标签,还能保证所有图片或其他相关内容被加载。要得到这个事件,你应该这样写:

    window.addEventListener('load', function() {...})
    

    Or using jQuery:

    或使用jQuery:

    $(window).on('load', function() {
     console.log('All assets are loaded')
    })
    

#5


9  

If you wanna call a js function in your html page use onload event. The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET. This attribute may be used with BODY and FRAMESET elements.

如果想在html页面中调用js函数,请使用onload事件。onload事件发生在用户代理完成加载窗口或框架集中的所有帧时。这个属性可以与BODY和FRAMESET元素一起使用。

<body onload="callFunction();">
....
</body>

#6


6  

This way you can handle the both cases - if the page is already loaded or not:

这样您就可以处理这两种情况——如果页面已经加载或没有加载:

document.onreadystatechange = function(){
    if (document.readyState === "complete") {
       myFunction();
    }
    else {
       window.onload = function () {
          myFunction();
       };
    };
}

#7


2  

If you are not using any JS frameworks, this project is the best way to get the dom ready state, with cross browser compatibility

如果您不使用任何JS框架,这个项目是获得具有跨浏览器兼容性的dom就绪状态的最佳方式

https://github.com/ded/domready/blob/master/ready.js

https://github.com/ded/domready/blob/master/ready.js

#8


1  

If you're already using jQuery, you could try this:

如果您已经使用jQuery,您可以尝试以下方法:

$(window).bind("load", function() {
   // code here
});

#9


1  

window.onload = () => {
  // run in onload
  setTimeout(() => {
    // onload finished.
    // and execute some code here like stat performance.
  }, 10)
}

#10


1  

I can tell you that the best answer I found is to put a "driver" script just after the </body> command. It is the easiest and, probably, more universal than some of the solutions, above.

我可以告诉您,我找到的最佳答案是在命令之后放置“driver”脚本。它比上面的一些解决方案更简单,也可能更普遍。

The plan: On my page is a table. I write the page with the table out to the browser, then sort it with JS. The user can resort it by clicking column headers.

计划:在我的页面上是一张桌子。我将表写在浏览器中,然后用JS对它进行排序。用户可以通过单击列标题来使用它。

After the table is ended a </tbody> command, and the body is ended, I use the following line to invoke the sorting JS to sort the table by column 3. I got the sorting script off of the web so it is not reproduced here. For at least the next year, you can see this in operation, including the JS, at static29.ILikeTheInternet.com. Click "here" at the bottom of the page. That will bring up another page with the table and scripts. You can see it put up the data then quickly sort it. I need to speed it up a little but the basics are there now.

在表结束了命令之后,正文结束后,我使用下面的行来调用排序JS来按第3列对表进行排序。我从网上下载了排序脚本,所以这里没有复制。至少在接下来的一年里,您可以在static29 iliketheinternet.com上看到这个操作,包括JS。点击页面底部的“这里”。这会带来另一个包含表和脚本的页面。你可以看到它放置数据然后快速排序。我需要加快一点速度,但是现在基本的东西已经存在了。

</tbody></body><script type='text/javascript'>sortNum(3);</script></html>

MakerMikey

MakerMikey

#11


0  

Try this jQuery:

试试这个jQuery:

$(function() {
 // Handler for .ready() called.
});

#12


0  

I'm using web components so that works for me:

我使用的是web组件,所以这对我来说是可行的:

document.addEventListener('WebComponentsReady', function() {
       document.querySelector('your-element').show();
});

#13


0  

call a function after complete page load set time out

在完成页面加载设置时间后调用函数

setTimeout(function() {
   var val = $('.GridStyle tr:nth-child(2) td:nth-child(4)').text();
	for(var i, j = 0; i = ddl2.options[j]; j++) {
		if(i.text == val) {      
			ddl2.selectedIndex = i.index;
			break;
		}
	} 
}, 1000);

#14


-2  

Put your script after the completion of body tag...it works...

在body标签完成后,把你的脚本放到…它的工作原理……

#1


112  

this may work for you :

这可能对你有用:

document.addEventListener('DOMContentLoaded', function() {
   // your code here
}, false);

or if your comfort with jquery,

或者如果你喜欢jquery,

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

$(document).ready() fires on DOMContentLoaded, but this event is not being fired consistently among browsers. This is why jQuery will most probably implement some heavy workarounds to support all the browsers. And this will make it very difficult to "exactly" simulate the behavior using plain Javascript (but not impossible of course).

$(document).ready()在DOMContentLoaded后触发,但是在浏览器之间并没有持续地触发这个事件。这就是为什么jQuery很可能会实现一些繁重的工作区来支持所有的浏览器。这将使“精确”模拟使用普通Javascript的行为变得非常困难(当然也不是不可能)。

as Jeffrey Sweeney and J Torres suggested, i think its better to have a setTimeout function, before firing the function like below :

正如Jeffrey Sweeney和J Torres所建议的,我认为最好先有一个setTimeout函数,然后再触发如下函数:

setTimeout(function(){
 //your code here
}, 3000);

#2


27  

If you can use jQuery, look at load. You could then set your function to run after your element finishes loading.

如果可以使用jQuery,请查看load。然后可以将函数设置为在元素加载完成后运行。

For example, consider a page with a simple image:

例如,考虑一个具有简单图像的页面:

<img src="book.png" alt="Book" id="book" />

The event handler can be bound to the image:

事件处理程序可以绑定到图像:

$('#book').load(function() {
  // Handler for .load() called.
});

If you need all elements on the current window to load, you can use

如果需要加载当前窗口中的所有元素,可以使用

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

#3


14  

jQuery has excellent shorthand:

jQuery具有良好的速记法:

$(function(){

   // here code anything you want to run after page load

});

The below code is NO LONGER recommended!

document.onreadystatechange = function(){
   if(document.readyState === 'complete'){
      ............................
   }
}

because changes document property globally, instead of attaching a function to load event. So, DONT USE THAT.

因为它改变了全局的文档属性,而不是附加一个函数来加载事件。所以,不要使用。

#4


12  

I'm little bit confuse that what you means by page load completed, "DOM Load" or "Content Load" as well? In a html page load can fire event after two type event.

我有点搞不懂你所说的页面加载完成,“DOM load”或者“Content load”是什么意思?在html页面中,加载可以在两个类型事件之后触发事件。

  1. DOM load: Which ensure the entire DOM tree loaded start to end. But not ensure load the reference content. Suppose you added images by the img tags, so this event ensure that all the img loaded but no the images properly loaded or not. To get this event you should write following way:

    DOM load:确保加载的整个DOM树开始结束。但不能确保加载引用内容。假设您通过img标记添加了图像,因此此事件确保所有img都已加载,但没有正确加载图像。要得到这个事件,你应该这样写:

    document.addEventListener('DOMContentLoaded', function() {
       // your code here
    }, false);
    

    Or using jQuery:

    或使用jQuery:

    $(document).ready(function(){
    // your code
    });
    
  2. After DOM and Content Load: Which indicate the the DOM and Content load as well. It will ensure not only img tag it will ensure also all images or other relative content loaded. To get this event you should write following way:

    在DOM和Content Load之后:这也表示DOM和Content Load。它不仅能保证img标签,还能保证所有图片或其他相关内容被加载。要得到这个事件,你应该这样写:

    window.addEventListener('load', function() {...})
    

    Or using jQuery:

    或使用jQuery:

    $(window).on('load', function() {
     console.log('All assets are loaded')
    })
    

#5


9  

If you wanna call a js function in your html page use onload event. The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET. This attribute may be used with BODY and FRAMESET elements.

如果想在html页面中调用js函数,请使用onload事件。onload事件发生在用户代理完成加载窗口或框架集中的所有帧时。这个属性可以与BODY和FRAMESET元素一起使用。

<body onload="callFunction();">
....
</body>

#6


6  

This way you can handle the both cases - if the page is already loaded or not:

这样您就可以处理这两种情况——如果页面已经加载或没有加载:

document.onreadystatechange = function(){
    if (document.readyState === "complete") {
       myFunction();
    }
    else {
       window.onload = function () {
          myFunction();
       };
    };
}

#7


2  

If you are not using any JS frameworks, this project is the best way to get the dom ready state, with cross browser compatibility

如果您不使用任何JS框架,这个项目是获得具有跨浏览器兼容性的dom就绪状态的最佳方式

https://github.com/ded/domready/blob/master/ready.js

https://github.com/ded/domready/blob/master/ready.js

#8


1  

If you're already using jQuery, you could try this:

如果您已经使用jQuery,您可以尝试以下方法:

$(window).bind("load", function() {
   // code here
});

#9


1  

window.onload = () => {
  // run in onload
  setTimeout(() => {
    // onload finished.
    // and execute some code here like stat performance.
  }, 10)
}

#10


1  

I can tell you that the best answer I found is to put a "driver" script just after the </body> command. It is the easiest and, probably, more universal than some of the solutions, above.

我可以告诉您,我找到的最佳答案是在命令之后放置“driver”脚本。它比上面的一些解决方案更简单,也可能更普遍。

The plan: On my page is a table. I write the page with the table out to the browser, then sort it with JS. The user can resort it by clicking column headers.

计划:在我的页面上是一张桌子。我将表写在浏览器中,然后用JS对它进行排序。用户可以通过单击列标题来使用它。

After the table is ended a </tbody> command, and the body is ended, I use the following line to invoke the sorting JS to sort the table by column 3. I got the sorting script off of the web so it is not reproduced here. For at least the next year, you can see this in operation, including the JS, at static29.ILikeTheInternet.com. Click "here" at the bottom of the page. That will bring up another page with the table and scripts. You can see it put up the data then quickly sort it. I need to speed it up a little but the basics are there now.

在表结束了命令之后,正文结束后,我使用下面的行来调用排序JS来按第3列对表进行排序。我从网上下载了排序脚本,所以这里没有复制。至少在接下来的一年里,您可以在static29 iliketheinternet.com上看到这个操作,包括JS。点击页面底部的“这里”。这会带来另一个包含表和脚本的页面。你可以看到它放置数据然后快速排序。我需要加快一点速度,但是现在基本的东西已经存在了。

</tbody></body><script type='text/javascript'>sortNum(3);</script></html>

MakerMikey

MakerMikey

#11


0  

Try this jQuery:

试试这个jQuery:

$(function() {
 // Handler for .ready() called.
});

#12


0  

I'm using web components so that works for me:

我使用的是web组件,所以这对我来说是可行的:

document.addEventListener('WebComponentsReady', function() {
       document.querySelector('your-element').show();
});

#13


0  

call a function after complete page load set time out

在完成页面加载设置时间后调用函数

setTimeout(function() {
   var val = $('.GridStyle tr:nth-child(2) td:nth-child(4)').text();
	for(var i, j = 0; i = ddl2.options[j]; j++) {
		if(i.text == val) {      
			ddl2.selectedIndex = i.index;
			break;
		}
	} 
}, 1000);

#14


-2  

Put your script after the completion of body tag...it works...

在body标签完成后,把你的脚本放到…它的工作原理……