Can AJAX-functionality be loaded dynamically?
October 30th, 2007 |Uhm, what?
Okay, that’s the basic thought: A user visits the website. PHP recognizes a new session and therefore creates a variable $ajaxAvailable and sets it to false. The first page being displayed to the user only includes one simple AJAX-statement which tries to GET data. If AJAX isn’t available, or JavaScript is disabled, nothing happens. If AJAX is available the PHP-application recognizes the request, therefore sets $ajaxAvailable true for the current session. This way it can act different when displaying pages.
Utilizing Smarty (I guess any other template engine will do as well, I’m just into Smarty) one could send less data if AJAX is available, like so:
{if $ajaxAvailable}
<h1>header</h1>
<p>preview</p>
<a rel="getMore" href="fullarticle.php">full article</a>
{else}
<h1>header</h1>
<p>full article</p>
{endif}
What about the original question, then?
Yeah, ok. Well I was just thinking that most pages would offer AJAX-functionality already on the first page. So this method would either require to load AJAX and non-AJAX contents on first access, or the page needs to be reloaded or other quirky dumb un-usable stuff. But we could get around that if the GET-request we sent to check for AJAX in the first place could then deliver this AJAX-functionality. Like importing a script on the fly. I see that on the first attempt one has to load the non-AJAX stuff anyways (in the case AJAX is not available, that is), but somehow I think this could be useful in some way. But probably I’m just plain wrong.
As life is a google-search for the terms “load javascript dynamically” gives, as a first result, this article: Dynamically Loading External JavaScript Files and, after some more digging around, Javascript includes – yet another way of RPC-ing. Searching and digging are nice.