Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd like to offer an alternative for those who are trying to build external libraries and trying to follow the unobtrusive javascript mindset as much as possible within .NET.</p> <p>pageLoad is an excellent method to automatically wire up AJAX events which should fire on every page load (whether that load comes from a back button navigation to this page, a forward button navigation to the page, an AJAX callback, a standard page load, etc.), and since you don't have to worry about waiting for the ScriptManager to exist in the DOM, and it's named in a way that makes sense, for the most part (pageLoad vs. body.onload is slightly confusing for non .NET coders, but for a .NET person, it makes sense that pageLoad fires EVERY page load, including after callbacks, since the behavior is identical for the server side Page_Load). That being said, your concerns are good ones - you don't want two instances of pageLoad on a given page, as it will break. Here's a straight javascript solution which is safe for your developers to all follow, allows the use of pageLoad, doesn't fret about the DOM existing, ensures no code collisions, and works wonderfully for us.</p> <p>In your main javascript library, define pageLoad, as well as a helper function:</p> <pre><code>if (!pageLoad) { var pageLoad = function (sender, args) {}; }; if (!mylibrarynamespace) {var mylibrarynamespace = {};}; if (!mylibrarynamespace.registerStartupScript) mylibrarynamespace.registerStartupScript = function (fn) { /* create local pointer for added function */ var f = fn; /* create pointer to existing pageLoad function */ var pLoad = pageLoad; /* add new function pointer to pageLoad by creating new anonymous function (search Google for "javascript enclosures" for why pl and f will persist with this newly defined anonymous function) */ pageLoad = function (sender, args) { pLoad(sender,args); f(sender, args); } } </code></pre> <p>Then, to use it anywhere in your client side code, just do the following:</p> <pre><code>mylibrarynamespace.registerStartupScript( function (sender, args){ /* do my AJAX always enabled startup code logic here*/ } ); </code></pre> <p>To make changing the functionality more easy, I recommend that the passed in anonymous function call a function within that page or control's subset of your library so that you only need to change your library's function declaration (in the file or at runtime dynamically) to change how the pageLoad for that particular part of your site works.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload