1. Technology
Send to a Friend via Email

Adding Javascript from Javascript

clr gif
Join the Discussion

Questions? Comments?

One thing that Javascript is often used for is to update the content of a web page. This is best done using the Document Object Model (DOM) but is sometimes done using innerHTML.

One piece of HTML that you may want to add to your web page is the script tags that will attach another Javascript to your page allowing further Javascript code to then be run. A simple function can perform this processing for us using the DOM.

function addJavascript(jsname,pos) {
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsname);
th.appendChild(s);
}

This function adds the necessary script tag into the end of the head or body section of the page for you. All that you then need to do from your Javascript in order to add another external javascript into the page is to call that function passing it the name of the file that contains the extra code that you want to include and whether to add it to the end of the head or the end of the body.

addJavascript('newExternal.js','body');
addJavascript('newExternal2.js','head');

Once the script tags have been added to the page you can then call any functions that you want from within that file.

See More About

©2014 About.com. All rights reserved.