[英]Run JavaScript after all window.onload scripts have completed?
我有一个 asp.net 页面,它加载了一些 JavaScript 脚本。 其中一个脚本将一些控件加载到页面中,并将它们附加到window.onload
事件中的主体。
我需要通过隐藏代码注入一个脚本来调用依赖于在window.onload
中创建的控件的脚本方法。 这是行不通的,因为我打的每个电话总是很早,而且目前还没有创建控件。 例如,如果我在超链接中通过onclick
调用它,它会起作用,因为控件已经在onload
中创建。
所以:
<script type="text/javascript" src="/Scripts/somefile.js"></script>
addEvent(window, "load", blabla);
- 上面的 js 准备了一些要附加到 onload 事件主体的控件
在后面的代码中,我尝试通过this.Page.ClientScript.RegisterStartupScript
或this.Page.ClientScript.RegisterClientScriptBlock
或任何应该调用上面 .js 上的方法的方式向页面编写脚本,这取决于加载的控件onload
事件。 此步骤失败,因为该控件尚不在 DOM 中。
关于在window.onload
事件之后如何拨打电话的任何建议?
创建一个函数数组:
<script>
var onLoadFunctions = [];
function addOnLoad(funcName) {
onLoadFunctions[onLoadFunctions.length] = funcName;
}
function executeOnLoad() {
for (var i=0; i<onLoadFunctions.length; i++) onLoadFunctions[i]();
}
addOnLoad(foobar);
addOnLoad(blabla);
addOnLoad(theother);
window.onload = executeOnLoad;
</script>
您可以像注册启动脚本一样注册js文件:
this.Page.ClientScript.RegisterClientScriptInclude("scriptKey", "/Scripts/somefile.js");
使用原型JavaScript ,可以在DOM准备就绪时调用脚本( 请参阅此处的API ):
document.observe("dom:loaded", function() {
alert('The DOM is ready.');
});
我建议将在onload
事件中加载的脚本移动到dom:loaded
事件。
代替window.onload,您可以在示例代码片段下方使用document.onreadystatechange事件。
document.onreadystatechange=onReady;
function onReady() {
if (document.readyState=="complete") {
alert('The document ready state is "complete"')
}
我尝试了几种方法都没有成功。 我只是更改了业务需求,并且脚本是由用户操作触发的,而不是通过后面的代码注入的脚本。
但是对于寻求答案的人,有几种可能的解决方案可以解决您的问题。
onLoad
中使用timeout
来安排您的脚本稍后运行。function mustRunLast () {
// your "must run after everything else" code here
}
document.addEventListener('load', function(){
// adjust the delay as you like, 500 millis is a bit long
setTimeout(mustRunLast, 500)
})
以上迫使您猜测完成其他onLoad
脚本需要多长时间。 为了安全起见,您必须使用较长的延迟,但这可能是不可取的。 但是如果您有一些 state 可以检查以验证您所依赖的其他脚本是否已运行,您可以使用短暂的延迟并让脚本继续重试直到一切准备就绪:
const mustRunLast = function() {
// check some state to see if the other scripts
// did their thing. If not, schedule self to retry later
if (<not ready yet>) {
setTimeout(mustRunLast, 50)
return
}
// your "must run after everything else" code here
}
document.addEventListener('load', mustRunLast)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.