1
votes

I have an asp.net page that loads some javascript scripts. One of those scripts loads some controls into the page appending them to the body in the window.onload event.

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

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

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 step fails because the control is not in the DOM yet.

Any suggestion on how make the call after the window.onload event?

6

6 Answers

3
votes

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

Instead window.onload, you can use document.onreadystatechange event for this,, below the sample snippet..

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

If you can use jQuery

then you can call the script after the DOM load is complete.

$(document).ready()

Introducing $(document).ready()

1
votes

You can register the js file like you register the startup script:

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

Using Prototype JavaScript, you can have scripts called when the DOM is ready (see the API here):

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.

0
votes

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.