Javascript function must be executed on every page load
I am looking at an asp.net 2 web application that I maintain (but did not write).
Some of the things that should happen on page load fail, but only occasionally, and it seems as if you are using Firefox 3 inside a virtual machine. JQuery and asp.net Ajax are used.
An important function that should run every time (but not) is attached with the following Javascript:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){ Sys.Application.add_load(ImportantFunction); });
$(document).ready(function(){ Otherstuff(); });
$(document).ready(function(){ MoreStuff(); });
//]]>
</script>
But if I use firebug to set a breakpoint in ImportantFunction (), it doesn't get hit on page load in firefox 3, but it gets hit by ajax update.
There are several calls to $ (document) .ready on the page as they come from different parts of the asp.net code behind it. Yes, they do everything.
source to share
Try the following:
<script type="text/javascript">
//<![CDATA[
$(document).ready(ImportantFunction);
$(document).ready(Otherstuff);
$(document).ready(MoreStuff);
//]]>
</script>
Place the call Sys.Application.add_load
in the body ImportantFunction
, that is, in your .js file:
function importantFunction()
{
Sys.Application.add_load(ImportantFunction);
}
Edit: I'm not sure if it is possible to add multiple functions to be executed on the event $(document).ready
. It might help if you did this instead:
<script type="text/javascript">
//<![CDATA[
$(document).ready(init);
//]]>
</script>
And in init
you can include calls to all other functions, for example:
function init()
{
importantFunction();
otherStuff();
moreStuff();
//Any other functions to be called upon page load go here
}
It will also make the code easier to read :)
source to share
Is there a reason you can't use the ASP.NET AJAX pageLoad function instead of $ (document) .ready ()?
function pageLoad(sender, args)
{
ImportantFunction();
OtherStuff();
MoreStuff();
}
This is part of the lifecycle of an ASP.NET AJAX client page, and all JavaScript code inside will execute on every page load, including asynchronous callbacks.
source to share
You are using jQuery to attach a "load" method, which then in turn attaches a load event, and I think this is your problem.
$(document).ready
and Sys.Application.add_load
- almost the same, or so I understand. I'm not sure what order the browser will execute them in.
I suggest removing the call to the Sys.Application.add_load
wrapper on ImportantFunction
so you don't try to hook into the event stack that has already been fired.
source to share
According to this recent blog post , this is a bug (or at least a bug) in FireFox 3. It suggests calling your important function PageLoad
to get it to work cross-browser, although I'm not sure if that will work or not.
source to share