-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?

5
  • 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. Commented Mar 22, 2016 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 Commented Mar 22, 2016 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. Commented Mar 22, 2016 at 22:10
  • @Whymarrh, not full duplicate because of jquery Commented Mar 22, 2016 at 22:16
  • @Qwertiy sorry, jQuery here makes very little difference. The question is exactly the same. Commented Mar 22, 2016 at 22:27

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

-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>

2 Comments

sorry, it doesn't work
@bildstein, as you see, it does.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.