Why does jquery.load () ignore <script>?

I have a general a.html page that looks like this:

<html> <head> <script type="text/javascript" src="xyz.js" > </script> </head> <body> <div> ... </div> </body> </html> 

In b.html, I use the jquery .load() function for the div .

 $("#myDiv").load("a.html") 

It works. The content of xyz.js is loaded with a.html. But why is there no <script> ? I open firebug to see the source. There is a, but not a <script> .

I want <script> because I need to find the relative path. ( this question )

Edit: I tried using .get() and .html() . Did not help.

Edit2: the title is not very suitable. Running xyz.js. But not <script> .

+4
source share
2 answers

The .load() function purposefully extracts <script> tags from the loaded content. When you give it a simple download URL, it will execute scripts after loading the content and adding it to the DOM. However, if you use the trick of adding a selector after the URL in the first argument:

 $('#foo').load("http://some.domain.com/blah #special-div"); 

then it breaks the <script> tags, but does not execute them.

Why? I dont know.

Now note that loading the entire page from the <html> down into the element of another page will create some kind of Frankenstein DOM monster, if the browser does it at all. Typically, when you use ".load ()" to capture pieces of content to refresh a page, your server should respond with a fragment of the page, not everyone. The jQuery deal with selector resolution after the actual URL is for you to cut out a page fragment, which is really cool, but has the disadvantage that the scripts will not be executed in this case.

+6
source

Because it cannot run the script inside the <SCRIPT> . jQuery has .getScript() for calling scripts only. Check here

0
source

All Articles