Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Apr 2003
    Location
    Montreal, QC
    Posts
    340
    Thanks
    3
    Thanked 2 Times in 2 Posts

    Question Inserting script into <script> tag

    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:
    Code:
    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:
    Code:
    // 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?
    Search for Laughter or Just Search?
    GiggleSearch.org
    Blog: www.johnbeales.com
    All About Ballet: www.the-ballet.com

  • #2
    Regular Coder
    Join Date
    Mar 2006
    Posts
    728
    Thanks
    35
    Thanked 132 Times in 123 Posts
    Code:
    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
    Code:
    alert(document.getElementsByTagName('script').length+" script elements");
    
    addLiteralJS('function countscripts(str){'+
    'alert(document.getElementsByTagName("script").length+" script elements")}');
    
    countscripts();
    Last edited by mrhoo; 08-08-2008 at 11:57 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •