[英]Javascript function should be running on every page load

I am looking at an 2 web application that I am maintaining (but did not write).

我正在查看我正在維護的 2 Web應用程序(但沒有寫)。

Some things that should happen on the page loading do not, but only sometimes, and it seems to be if you are using Firefox 3 inside a VM. JQuery and Ajax are used.

在頁面加載時應該發生的一些事情不會,但只是有時,似乎是你在VM中使用Firefox 3。使用JQuery和 Ajax。

The important function that should run every time (but does not) is attached by the following Javascript:


<script type="text/javascript">
$(document).ready(function(){ Sys.Application.add_load(ImportantFunction); });   
$(document).ready(function(){ Otherstuff(); });
$(document).ready(function(){ MoreStuff(); });

But if I use firebug to set a breakpoint inside ImportantFunction(), it is not hit on page load in firefox 3, but it is hit on an ajax update.

但是,如果我使用firebug在ImportantFunction()中設置一個斷點,它在firefox 3中的頁面加載時不會被擊中,但它會在ajax更新中被擊中。

In the page there are multiple calls to $(document).ready since they come from different parts of the code behind it. Yes, they do all execute.


4 个解决方案


Try this:

<script type="text/javascript">

Put the call to Sys.Application.add_load in the body of ImportantFunction, i.e in your .js file:


function importantFunction()

Edit: I'm not sure if its possible to add multiple functions to be run on $(document).ready event. It might help if you did this instead:


<script type="text/javascript">

And in init you can include calls to all the other functions, i.e:


function init()
   //Any other functions to be called upon page load go here

It will also make the code easier to read :)



Is there any reason why you can't use the ASP.NET AJAX pageLoad function instead of $(document).ready()?

是否有任何理由不能使用ASP.NET AJAX pageLoad函數而不是$(document).ready()?

function pageLoad(sender, args)

This is part of the ASP.NET AJAX client page lifecycle and all JavaScript code inside will be executed on every page load, including asynchronous postbacks.

這是ASP.NET AJAX客戶端頁面生命周期的一部分,內部的所有JavaScript代碼都將在每個頁面加載時執行,包括異步回發。


You're using jQuery to attach a "load" method which then in-turn attaches a load event and I think this is where your problem is.


$(document).ready and Sys.Application.add_load are pretty much the same, or so my understanding goes. I'm not really sure in which order the browser will execute them though.


I'd suggest removing the Sys.Application.add_load wrapper call on ImportantFunction so you're not trying to attach to an event stack that has already fired.



According to this recent blog posting, this is a bug (or at least a misfeature) in FireFox 3. He suggests naming your important function PageLoad to get it to work cross-browser, though I'm not sure if that will work or not.

根據最近的博客文章,這是FireFox 3中的一個錯誤(或至少是一個錯誤)。他建議命名你的重要功能PageLoad讓它跨瀏覽器工作,雖然我不確定這是否會起作用。



粤ICP备14056181号  © 2014-2021