...

View Full Version : Is it possible to load additional javascript with javascript?



ColdCoil
12-31-2005, 08:31 AM
Ok, so here is what I want to do, but I don't know if it can be done.

I want to have a big library of javascript that will modify DOM objects based on their ID, but because this will be a big library, I want to only send to the user what is needed to modify their page.

So this is what I was thinking. With some mechanism decide which javascript files need to be retrieved from the server and by using some ajax type http request get the files and then make the browser load them. This way only one base javascript file that does the downloading and the library files necessary are transferred.

So my question is, can javascript download additional javascript and load it?

vwphillips
12-31-2005, 10:34 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>

<script language="JavaScript" type="text/javascript">
/*<![CDATA[*/

var JSAdd;
var CSSAdd;

function AddJS(name){
if (getFile(name)==null){ return; }
head=document.getElementsByTagName('HEAD')[0];
// next line removes the previously added External JavaScript
if (JSAdd){ head.removeChild(JSAdd); }
JSAdd=document.createElement('SCRIPT');
JSAdd.type='text/javascript';
JSAdd.src=name;
head.appendChild(JSAdd);
}

function AddCSS(name){
if (getFile(name)==null){ return; }
head=document.getElementsByTagName('HEAD')[0];
// next line removes the previously added StyleSheet
if (CSSAdd){ head.removeChild(CSSAdd); }
CSSAdd=document.createElement('LINK');
CSSAdd.rel='stylesheet';
CSSAdd.type='text/css';
CSSAdd.href=name;
head.appendChild(CSSAdd);
}

function getFile(filename){
oxmlhttp = null;
try {
oxmlhttp = new XMLHttpRequest();
oxmlhttp.overrideMimeType("text/xml");
}
catch(e){
try { oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch(e){ return null; }
}
if(!oxmlhttp) return null;
try {
oxmlhttp.open("GET",filename,false);
oxmlhttp.send(null);
}
catch(e){ return null; }
return oxmlhttp.responseText;
}


function Test(){
alert('An External JavaScript\nhas not been Added');
}

/*]]>*/
</script>

</head>

<body>
<input type="button" name="" value="Add JS fred.js" onclick="AddJS('fred.js');" /><br />
<input type="button" name="" value="Add JS tom.js" onclick="AddJS('tom.js');" /><br />
<input type="button" name="" value="Test" onclick="Test();" />
<br />
<br />
<input type="button" name="" value="Add CSS ss1.css" onclick="AddCSS('ss1.css');" /><br />
<input type="button" name="" value="Add CSS ss2.css" onclick="AddCSS('ss2.css');" /><br />
<span class="color" >Some Test Text</span>
</body>

</html>

DHTML Kitchen
01-01-2006, 03:05 AM
check out dojotoolkit.org to see how they did it. Top class javascript programmers, they are.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum