Dynamically Loading JavaScript Files - by PHP Expert


As you develop web applications that make use of Ajax to dynamically load content on a web page, you might find that you also need to dynamically load a JavaScript file. The remainder of this blog post describes a function to achieve exactly this.

This function relies on the Prototype JavaScript framework, which hopefully you are using already.

In order to load a JavaScript file you need to insert a new script element into the Document Object Model (DOM). While in theory this sounds relatively straightforward, you need to ensure the code has finished loading before you can make use of it.

This is achieved by observing the onload event on the <script> element. Unfortunately, doing so will work on all browsers except for Internet Explorer, which instead requires that you monitor the onreadystatechange event.

The following function allows you to easily load JavaScript files in real time.

<script type="text/javascript">
function loadJs(path, onload)
{
var script = new Element(\'script\', {
src : path,
type : \'text/javascript\'
});

if (onload) {
if (Prototype.Browser.IE) {
Event.observe(script, \'readystatechange\', function(e) {
if (this.readyState == \'loading\')
return;

onload();
}.bind(script));
}
else
Event.observe(script, \'load\', onload.bind(script));
}

$$
(\'head\')[0].insert(script);
}
<
/script>

The following code shows an example of loading a file called scripts.js, in which a function called myFunction() is defined. This function is not available until the scripts.js file is loaded.

The script DOM element is passed as the first and only argument to the callback function.

<script type="text/javascript">
loadJs(\'/path/to/scripts.js\', function(script) {
myFunction();
});
<
/script>

Alternatively, you could define the callback function separately, as in the following:

<script type="text/javascript">
function onScriptLoaded()
{
myFunction();
}

loadJs(\'/path/to/scripts.js\', onScriptLoaded);
<
/script>

This function begins by creating the new DOM element (without yet adding it to the DOM). These four lines would be the equivalent to the HTML <script type="text/javascript" src="/path/to/file.js"></script>

Next we check whether or not a callback function has been defined (since it is optional). If the function is defined, we then check whether or not the browser is Internet Explorer.

If the browser is Internet Explorer, we observe the onreadystatechange event. This event is triggered when the file starts to load and when it has completed loading. Obviously we are only interested in when it has completed, so we check the readyState property.

For all other browsers we simply observe the onload event, which is fired only when the file has completed loading (as well as if the file is already in the browser cache).

In both cases, the Prototype bind() method is called in order to bind the script element to the callback. This means that when you refer to this in the callback, it refers to the script element.

Finally, the element is inserted into the DOM. This is done by inserting it into the head of the HTML document (retrieved using the Prototype $$() method.

The element should be inserted into the DOM as the final step since if it\'s done before observing the events, the events may be fired immediately if the file is already in the browser cache.

No comments

Enter your email address:

Delivered by FeedBurner

OR

 Subscribe in a reader

 
jQuery UI provides a comprehen
 
Program Plan   I drafted a p
 
I present to you my skills, ac
 
Introduction One of the issue
 
If you are a PHP developer and
 
cURL is a great tool to help y
 
cformsII cforms is a powerful
 
  The lack of Unicode su
 
History PHP-GTK was origina
 
Performance on the web is stra
 
Listen t
 
What\'s the number one cost in
 
When you\'re discussing the In
 
Classe
 
A service-oriented architectur
 
Introduc
 
PHP Crons and Linux Linux has
 
Cross site scripting (XSS) is
 
What Makes a Web 2.0 Applicati
 
As you develop web application
 
Cryptogr
 
Posting
 
Have you
 
Resources The Google API - ht
 
Get Started
 
Output B
 
If you r
 
PHP has some really sweet new
 
There were some new php.ini di
 
In PHP 5 there are some new fu
 
The following code implements
 
The following code snippet imp
 
A fine implementation of the o
 
Exception handling PHP 5 adds
 
Support for dereferencing obje
 
Static members Classes defini
 
Explicit object cloning In or
 
final methods The final keywo
 
Interfaces Gives the ability
 
The new object oriented featur
 
Sometimes its the little thing
 
Consider your file is at locat
 
# If a method can be static, d