-2

I'm using eval() to execute all <script> tags after total rewrite of a div.

$("#content").find("script").each(function(){
    eval($(this).text());
});

It works well for inline-scripts, but has no effect on scripts like:

<script src="/path/to/externalScript.js"></script>

How come? Can I "force" the browser to load and execute also the external scripts?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
bildstein
  • 25
  • 3
  • 9
  • 2
    You arent suppose to use Eval anymore.. I got reamed out by the internet years ago when trying to use it. Opens you up for injection. – Fallenreaper Mar 22 '16 at 22:01
  • Yes I know, but it's the the only solution that i Know. I try to load a script after ajax response – bildstein Mar 22 '16 at 22:05
  • 1
    What does `$(this).text()` contain? Likely nothing as the `script` element doesn't have text content. You'd want to perform an Ajax request for the script, read its text content, and call `eval` on that. – Whymarrh Mar 22 '16 at 22:10
  • @Whymarrh, not full duplicate because of [tag:jquery] – Qwertiy Mar 22 '16 at 22:16
  • @Qwertiy sorry, jQuery here makes very little difference. The question is exactly the same. – Whymarrh Mar 22 '16 at 22:27

2 Answers2

0

Besides the very real issues with using eval, you are trying to eval the .text inside those script tags, which is essentially nothing.

When a <script> tag loads, it links in the external file as a resource to your page and executes the script. It does not render anything directly to the dom.

Thus you $(this).text() will return ''.

If you want to reload the external scripts, you will either need to force a page refresh, or potentially change the way you are pulling in those scripts: ex. jQuery.getScript alternative in native JavaScript

Community
  • 1
  • 1
ginman
  • 1,315
  • 10
  • 20
-2

$("body").css("background", "silver");

$("button").click(function () {
  $("script[src^='data:']").each(function () {
    var script = document.createElement('script');
    script.src = this.src;
    document.body.appendChild(script);
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="data:text/javascript,document.body.style.background='red'"></script>
<button>Go</button>
Qwertiy
  • 19,681
  • 15
  • 61
  • 128