views:

66

answers:

2

Hi,

i'm loading, using the JQuery ajax() method, an external page with both html and javascript code:

<script type="text/javascript" src="myfile.js"></script>
<p>This is some HTML</p>
<script type="text/javascript">
     alert("This is inline JS");
</script>

and setting the results into a div element, using the html() method.

While the html() method properly evaluates the inline JS code, it doesn't download and evaluate the external JS file "myfile.js".

Any tip for this issue?

+2  A: 

If you control the external page you could change this

<script type="text/javascript" src="myfile.js"></script>

to

<script type="text/javascript" src="http://host/path/myfile.js"&gt;&lt;/script&gt;

Demo: http://jsbin.com/ucomu3/3 loads http://jsbin.com/otopi/3 via $.ajax and sets the returned data via html() http://jsbin.com/otopi/3 contains an inline script tag and one with a full qualified URL in the src-attribute which points to http://jsbin.com/uyova3

So if you open http://jsbin.com/ucomu3/3 you see "This is some HTML" and two alerts which say "I'm the external local js" and "This is inline JS"

jitter
Changing the src path actually doesn't solve the problem.It seems that JQuery, when setting the results into the div with the html() method, doesn't download the external scripts from the specified location, and doesn't evaluates it's contents.
Marco
Yeah, because that's not JQuery's job. It's the job of the browser.
middus
The jQuery.getScript() method, as stated in the documentation, "Load a JavaScript file from the server using a GET HTTP request, then execute it." If it's possible, i would avoid parsing the "script" tags from the results, and then call explicitly the getScript() method for each of them.
Marco
Changing the src should solve the problem because jQuery calls the `evalScript` function for every `script` tag it finds in the `data` parameter passed in to the success function of the `$.ajax` call. So @middus you are just wrong as it actually is jQuery's job to load the scripts
jitter
Check expanded answer for demo links
jitter
+1  A: 

Try to use an absolute address in the src-attribute of your <script>.

middus