4

eval () does not execute external scripts (src = ...)

 2 years ago
source link: https://www.codesd.com/item/eval-does-not-execute-external-scripts-src.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

eval () does not execute external scripts (src = ...)

advertisements

This question already has an answer here:

  • eval() doesn't execute external (src=…) scripts 2 answers

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?


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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK