Sys.Application.add_load()与$(文件)。就绪()与页面加载() [英] Sys.Application.add_load() vs. $(document).ready() vs. pageLoad()
问题描述
我有了一些JavaScript需要在页面加载运行页。说JavaScript需要找到ServerControl,它与$确实找到()的客户端组件。
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().
当然,如果我直接发出我的code到页面上,它执行的页面被阅读,因为没有它取决于尚未被初始化失败。
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.
如果我把我的code一个页面加载()函数中,它运行得很好,因为asp.net自动线了名为pageLoad的任何功能的onload事件处理程序()。问题是,我真的不喜欢这个页面加载()解决方案 - 主要是因为它是一个单一的全球名称。如果我犯使用页面加载()约code,我只知道,其他一些程序员会复制的方式,不恰当的地方,我们打算与包括两个或多个不同的页面加载一个页面来结束()功能,其结果将是一堆神秘的错误,将采取永远跟踪。
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.
于是,我把我的code传递给jQuery的$(文件)。就绪()的匿名函数中。这种失败,因为它运行ServerControl的客户端组件存在了。
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.
于是,我把我的code()由Sys.Application.add_load传递给一个匿名函数中。这也失败了,因为Sys系统是不确定的。
So, I put my code inside an anonymous function passed to by Sys.Application.add_load(). This also fails, because Sys is undefined.
所以最后定居在把我的code里面Sys.Application.add_load(),然后把一个由$被调用的函数(文件)。就绪()。这工作,但它给几乎一样灼热的页面加载()。
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.
任何想法?
推荐答案
如果你有超过$ C $控制C-的背后,可以注册的JavaScript通过像在启动时运行:
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);
只要你的组件已经通过Sys.Application.add_init(加载)你应该罚款......
As long as your component has been loaded via Sys.Application.add_init() you should be fine...
这篇关于Sys.Application.add_load()与$(文件)。就绪()与页面加载()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!