Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

asp.net ajax - Sys.Application.add_load() vs. $(document).ready() vs. pageLoad()

I have page that has some javascript that needs to run at page load. Said javascript needs to locate the client-side component of a ServerControl, which it does with $find().

Of course, if I emit my code directly onto the page, it executes as the page is being read, and fails because nothing it depends on is yet initialized.

If I put my code inside a pageLoad() function, it runs just fine, because asp.net automatically wires up an onload handler for any function named pageLoad(). The problem is I really don't like the pageLoad() solution - mainly because it's a single global name. If I commit some code using pageLoad(), I just know that some other programmer is going to copy the approach, somewhere inappropriate, and we're going to end up with a page that includes two or more different pageLoad() functions, and the result will be a bunch of mysterious errors that will take forever to track down.

So, I put my code inside an anonymous function passed to jquery's $(document).ready(). This fails, because it runs before the ServerControl's client-side component exists.

So, I put my code inside an anonymous function passed to by Sys.Application.add_load(). This also fails, because Sys is undefined.

So I finally settle on putting my code inside Sys.Application.add_load(), and then put that inside a function called by $(document).ready(). This works, but it gives nearly as much heartburn as pageLoad().

<script type="text/javascript">
    $(document).ready(function(){
        Sys.Application.add_load(function(){
            var component = $find(<clientid>);
            if (component) { <do something> }
        });
    });
</script>

There has to be a better way of handling this.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have control over the code-behind, you can register the JavaScript to run at startup via something like:

this.Page.ClientScript.RegisterStartupScript(
    this.GetType(), 
    "StartupScript", 
    "Sys.Application.add_load(function() { functioncall(); });", 
    true);

As long as your component has been loaded via Sys.Application.add_init() you should be fine...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...