0

I am trying to insert script tag and its contents dynamically.

Now I have changed it to create a text node.

var text = "$(document).ready(function(){ $('.Picture1').onmouseover(function()      
{$('.tooltip').show();});});"
insertScript(text );

function insertScript(script_text) { 
 var script_tag = document.createElement('script'); 
 script_tag.type = "text/javascript";  
 var script = document.createTextNode(script_text); 
 script_tag.appendChild(script);  
 document.getElementsByTagName('head')[0].appendChild(script_tag); 
} 

I am trying to find it in script debugger (press F12 for IE) I am first inserting JQuery-1.7.1 dynamically and then the code above.

I want to insert both dynamically.

Thanks

Coder
  • 3,090
  • 8
  • 49
  • 85
  • Where are you looking to see if the script tag has been created? Please don't tell me you're looking at the page source. – Mahmoud Al-Qudsi Jun 26 '12 at 05:14
  • 1
    Why would you insert inline script into the current document? I can see dynamically adding an external script, but not an inline one... – nnnnnn Jun 26 '12 at 05:14
  • In addition, `$(document).ready()` would *never* be fired again, so... – Cranio Jun 26 '12 at 05:15
  • See http://stackoverflow.com/questions/1199676/can-i-create-script-tag-by-jquery – Suresh Kumar Jun 26 '12 at 05:27
  • What is your goal? Are you evaluating some info and then deciding what to include in the script tag? – codewaggle Jun 26 '12 at 05:36
  • The goal is to insert jquery dynamically. – Coder Jun 26 '12 at 05:39
  • That's not a goal, that's an implementation detail - unless you are doing this solely as a learning exercise? What's the underlying reason for inserting jQuery dynamically? May I suggest a light-weight script loader like [yepnope.js](http://yepnopejs.com/), which lets you specify a callback that will be run after the script loads? (You'd put your jQuery code in that callback instead of trying to insert it in its own script element.) – nnnnnn Jun 26 '12 at 06:13

1 Answers1

0

I suppose the only reason you want to insert script to the page dynamically is to execute it. In this case you can just use eval. It will to the same with the same pros and cons.

bjornd
  • 22,397
  • 4
  • 57
  • 73