简体   繁体   English

window.onload 脚本全部完成后运行 JavaScript?

[英]Run JavaScript after all window.onload scripts have completed?

I have an asp.net page that loads some JavaScript scripts.我有一个 asp.net 页面,它加载了一些 JavaScript 脚本。 One of those scripts loads some controls into the page appending them to the body in the window.onload event.其中一个脚本将一些控件加载到页面中,并将它们附加到window.onload事件中的主体。

I need to inject a script via code behind to call a method of the scripts that depends on the controls created in the window.onload .我需要通过隐藏代码注入一个脚本来调用依赖于在window.onload中创建的控件的脚本方法。 This doesn't work because every call I make it's always to early and the controls are not created at the moment.这是行不通的,因为我打的每个电话总是很早,而且目前还没有创建控件。 If I call it by, for instance, onclick in an hyperlink it works because the controls were already created in the onload .例如,如果我在超链接中通过onclick调用它,它会起作用,因为控件已经在onload中创建。

So:所以:

  1. <script type="text/javascript" src="/Scripts/somefile.js"></script>

  2. addEvent(window, "load", blabla); - the js above prepares some controls to be appended to the body on the onload event - 上面的 js 准备了一些要附加到 onload 事件主体的控件

  3. In the code behind I try to write a script to the page by this.Page.ClientScript.RegisterStartupScript or this.Page.ClientScript.RegisterClientScriptBlock or whatever way that should call a method on the.js above, which depends on the control loaded on the onload event.在后面的代码中,我尝试通过this.Page.ClientScript.RegisterStartupScriptthis.Page.ClientScript.RegisterClientScriptBlock或任何应该调用上面 .js 上的方法的方式向页面编写脚本,这取决于加载的控件onload事件。 This step fails because the control is not in the DOM yet.此步骤失败,因为该控件尚不在 DOM 中。

Any suggestion on how make the call after the window.onload event?关于在window.onload事件之后如何拨打电话的任何建议?

create an array of functions: 创建一个函数数组:

<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>

If you can use jQuery 如果可以使用jQuery

then you can call the script after the DOM load is complete. 那么您可以在DOM加载完成后调用脚本。

$(document).ready()

Introducing $(document).ready() 介绍$(document).ready()

您可以像注册启动脚本一样注册js文件:

this.Page.ClientScript.RegisterClientScriptInclude("scriptKey", "/Scripts/somefile.js");

Using Prototype JavaScript , you can have scripts called when the DOM is ready ( see the API here ): 使用原型JavaScript ,可以在DOM准备就绪时调用脚本( 请参阅此处的API ):

document.observe("dom:loaded", function() {
  alert('The DOM is ready.');
});

I would recommend moving the script that loads in the onload event to the dom:loaded event. 我建议将在onload事件中加载的脚本移动到dom:loaded事件。

Instead window.onload, you can use document.onreadystatechange event for this,, below the sample snippet.. 代替window.onload,您可以在示例代码片段下方使用document.onreadystatechange事件。

document.onreadystatechange=onReady;
  function onReady() {
      if (document.readyState=="complete") {
         alert('The document ready state is "complete"') 
      }

I tried several approaches with no success. 我尝试了几种方法都没有成功。 I just changed the business requirement and the script is fired by an user action, as opposed to a script injected via code behind. 我只是更改了业务需求,并且脚本是由用户操作触发的,而不是通过后面的代码注入的脚本。

But for someone looking for an answer, there are several possible candidates that may solve the problem in your case. 但是对于寻求答案的人,有几种可能的解决方案可以解决您的问题。

Use timeout within onLoad to schedule your script to run later.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)
})

The above forces you to guess how long it will take for your other onLoad scripts to finish.以上迫使您猜测完成其他onLoad脚本需要多长时间。 To play it safe, you'd have to use a long delay, but that is probably undesirable.为了安全起见,您必须使用较长的延迟,但这可能是不可取的。 But if you have some state that you can check to verify that the other scripts you're depending on have run, you can use a short delay and have the script keep retrying until things are ready:但是如果您有一些 state 可以检查以验证您所依赖的其他脚本是否已运行,您可以使用短暂的延迟并让脚本继续重试直到一切准备就绪:

Have your script check if things are ready, and schedule a retry for later if not让您的脚本检查一切是否准备就绪,如果没有准备好,稍后安排重试

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM