|
|

|
|
Dynamic data using the DOM and Remote Scripting
|
|
How it worksAs most of you probably know the DOM allows us to dynamically create almost any element that can be on a page, so
we use it to create a SCRIPT tag that we set a src to. When setting the src of a script tag then adding it
to the page the DOM browsers will try to load the script file that we specify.
function loadContent(file){
var head = document.getElementsByTagName('head').item(0)
var scriptTag = document.getElementById('loadScript');
if(scriptTag) head.removeChild(scriptTag);
script = document.createElement('script');
script.src = file;
script.type = 'text/javascript';
script.id = 'loadScript';
head.appendChild(script)
}
Let's go line by line;
var head = document.getElementsByTagName('head').item(0)
This just makes a short reference to the head element. Used later in the function.
var scriptTag = document.getElementById('loadScript');
This line tries to get the script tag called loadScript. The first time this
function is called this will return null because the tag does not exists.
if(scriptTag) head.removeChild(scriptTag);If the tag exists we remove it because we don't want all the old tags to stay in the page. In explorer you don't really have to do this, you can just set a src to the existing script element but that doesn't seem to work in Mozilla. script = document.createElement('script');
This creates a script tag.
script.src = file;This line sets the src of the script tag to the file that you specify when you call the function. script.type = 'text/javascript';We set the type of the script tag to text/javascript script.id = 'loadScript';Here we set the ID to loadScript so we can reach it with the second line in the code the next time this function is called. head.appendChild(script)Then we add the script tag to the page with the appendChild function. It's added to the head of the page. So if you call the function like this:
loadContent('myfile.js')
it's more or less
the same as adding a script tag with regular code like this:
<script type="text/javascript" id="loadScript" src="myfile.js"></script> Note that the file you load in a script tag like this HAVE to be a JS file. You cannot load another HTML file or whatever like this. It has to valid script inside the file. Ok, now we know how it works, but what can we do with it? There are tons of things we can do with this technique, let's start of with a simple example
Copyright ©2000-2002 DHTMLCentral.com, Bratta Communications. All rights reserved. |