0

I have a variable of the form :

var x =  '<script type="text/javascript" language="javascript"> ..lots of stuff...</script>
<script type="text/javascript" language="javascript"> ..even more of stuff...</script>'

and I want to insert it with jquery into my HTML code and execute it.

I tried using the append, html and eval without any luck.

Any ideas?

sample script:

<script type="text/javascript" language="javascript">
var clk = 'http://......';
</script>
<script type="text/javascript" language="javascript" src="http://...."></script>
<noscript>
<a href="http://...." target="_blank"><img src="http://..." width="120" height="600" border="0" alt=""></a>
</noscript>

this will in the end show an img, which will load asynchronously.

cs04iz1
  • 1,737
  • 1
  • 17
  • 30
  • 1
    Why not have your JS in an external file and just append the script tag to the body (with the src pointing to the file)? It should run as soon as the script tag is inserted. – evolutionxbox Aug 12 '15 at 14:02
  • i get the JS from a service – cs04iz1 Aug 12 '15 at 14:04
  • 2
    Escape in some way each `` tags, then it would work http://stackoverflow.com/a/236106/1414562 – A. Wolff Aug 12 '15 at 14:05
  • Including the script tag? Could you show us a sample of what you get from the service? – evolutionxbox Aug 12 '15 at 14:06
  • 1
    `$('body').append($(''))` works just fine. Are you sure the code ("stuff") is not broken? – Dmitry Ivanov Aug 12 '15 at 14:06
  • Post what you have tried. I think eval should work. If you're using jQuery, `$(somElement).html(theJsString)` should also work – Cristian Lupascu Aug 12 '15 at 14:06
  • @DmitryIvanov Not in some cases: https://jsfiddle.net/5xdr03hq/ while this one works https://jsfiddle.net/5xdr03hq/1/ – A. Wolff Aug 12 '15 at 14:10
  • @A.Wolff There may be something wrong with JSFiddle. Here it is in JSBin: http://jsbin.com/yodukexovo/1/edit?html,js,console – Cristian Lupascu Aug 12 '15 at 14:13
  • @w0lf AFAIK, jsFiddle gives the expected result here. I really don't know why this is handled differently on jsbin. Thx for the input! – A. Wolff Aug 12 '15 at 14:18
  • Do you have any error in console? – A. Wolff Aug 12 '15 at 14:19
  • using append i get: Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. and Uncaught TypeError: Cannot read property 'onmouseout' of null – cs04iz1 Aug 12 '15 at 14:21
  • @A.Wolff Your first jsfiddle link throws `Uncaught SyntaxError: Unexpected token ILLEGAL`, while in jsbin it works. – Cristian Lupascu Aug 12 '15 at 14:22
  • @w0lf Ya that's what i meant and this is expected behaviour. You can test it on codepen too, it would give same error. I don't know how this is handle on jsbin but AFAIK it should throw an error too, but it doesn't – A. Wolff Aug 12 '15 at 14:24

3 Answers3

0

You can use Jquery getScript:

//Moment example
if (typeof moment == "undefined") {
    var url = "~/assets/js/moment.js";
    $.getScript(url);
}

Or Jquery Function:

$(function(){   
    var test = "this.Foo = function() {alert('hi');}";
    var F=new Function (test);
    (new F()).Foo(); //Shows "Hi" alert
});

$(function(){ 
    var test = "this.Foo = function() {alert('hi');}";
    var F=new Function (test);
    (new F()).Foo(); //Shows "Hi" alert
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Hackerman
  • 12,139
  • 2
  • 34
  • 45
  • the append doesn't work, giving the following error : Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. – cs04iz1 Aug 13 '15 at 09:25
  • I deleted the `append` part because it doesn't seems to works well on most of the cases....so i add another approach using `Function` – Hackerman Aug 13 '15 at 12:21
0

Usually having </script> tags nested within other <script></script> tags will break things. You'll need to split them up like in the Javascript below to not cause browser issues.

Here is a working fiddle: https://jsfiddle.net/2vrfxrse/

Javascript

var jsCode = '<scr' + 'ipt>var executeTest = function(){ alert("This is a test."); }</scr' + 'ipt>';
$('head').append(jsCode);

HTML

<script>executeTest();</script>
Rick Burns
  • 1,538
  • 16
  • 20
0

This solution will probably work for your specific scenario:

var rx = new RegExp("<script .*?>(.*?)<\/script>", 'g');
var x = '<script type="text/javascript" language="javascript">alert("..lots of stuff...");</script><script type="text/javascript" language="javascript">alert("..even more of stuff...");</script>';
var res = rx.exec(x);

while (res) {
  var s = document.createElement("script");
  s.appendChild(document.createTextNode(res[1]));
  document.body.appendChild(s);
  res = rx.exec(x);
}

JSBin: http://jsbin.com/menocumiya/edit?html,js,console,output

Buzinas
  • 11,597
  • 2
  • 36
  • 58