0

Does jQuery.load(url) prevent scripts within the url content to run when the content is a fragment of a page?

For example, when the content is returned in the manner below, the embedded scripts are executed.

<html>
    <body>
        <script>
        </script>  
        <table>
        </table>
   </body>
</html>

However, when the content is returned in the following format, the scripts do not run.(note: there are no external references in the scripts)

<script>
</script>  
<table>
</table>

I am using

$('#myDiv').load(contentUrl); 

Thanks,

Ross Bush
  • 14,648
  • 2
  • 32
  • 55
  • 1
    Have you checked [this answer already](http://stackoverflow.com/questions/1317080/jquery-ajax-load-java-script-not-executing)? Maybe that helps :) – anno1337 Apr 25 '14 at 19:07
  • 1
    Scripts are executed in the browser, and pages loaded through AJAX calls are fetched directly from the web server as plain text. I would strongly discourage the approach of running scripts loaded from another page. If the scripts are yours, include them on your pages and trigger functionality when you need to. – Alexander Wallin Apr 26 '14 at 14:53

1 Answers1

1

If you TRUST, the source of the load, then you could do this:

$('#myDiv').load(contentUrl, function(){
   $(this).find('script').each(function(){
     eval(this);
   });
});  

Please note I said TRUST.

Alex Shilman
  • 1,547
  • 1
  • 11
  • 15
  • Yes, i get what you are saying about trust. And thanks, after two days of spinning my wheels your answer worked for me. However, it just proved what I thought might be the case. The script in the content is slowing rendering when placed in the dom. I was trying to get away from using an iframe where the content images were resized and the content rendered in 2 seconds. Using div.load() and div.html() takes 15 seconds with the same content when the scripts are evaluated :( – Ross Bush Apr 26 '14 at 13:22