...

View Full Version : Inserting script into <script> tag



johnnyb
08-09-2008, 12:16 AM
I'm trying to find a way to insert script into a script tag - not by setting a src.

I know how to do this:


var parent = document.getElementById('parent');
var st = document.createElement('script');
st.setAttribute('type','text/javascript');
st.setAttribute('src','some_js_file.js');
parent.appendChild(st);


But I want to do this:


// since I don't know how, this is pseudo-code
var parent = document.getElementById('parent');
var st = document.createElement('script');
st.setAttribute('type','text/javascript');
st.innerScript = 'some; javascript; statements;';
parent.appendChild(st);


Does anyone know how to do this cross-browser?

mrhoo
08-09-2008, 12:40 AM
function addLiteralJS(javascript_text){
var st = document.createElement('script');
st.setAttribute('type','text/javascript');
try{
st.appendChild(document.createTextNode(javascript_text));
}
catch(er){
if(st.text!==undefined)st.text= javascript_text;
}
document.getElementsByTagName('head')[0].appendChild(st);
}
// test case

alert(document.getElementsByTagName('script').length+" script elements");

addLiteralJS('function countscripts(str){'+
'alert(document.getElementsByTagName("script").length+" script elements")}');

countscripts();



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum