June 8, 2011

why does jquery's .load() ignore <script>?

Question by Lai Yu-Hsuan

I have a every common page a.html which looks like this:

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

In b.html, I use jquery’s .load() function to a div.

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

It works. The xyz.js’s content is loaded along with a.html. But why isn’t there a <script> tag? I open firebug to see the source. There is a’s but no a’s <script>.

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

Edit: I tried to use .get() and .html(). Didn’t help.

Edit2: The title is not very appropriate. The xyz.js runs. But no <script>.

Answer by Pointy

The “.load()” function purposefully strips out <script> tags from the loaded content. When you give it a plain URL to load, it will execute the 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 strips the <script> tags but it does not execute them.

Why? I don’t know.

Now, please note that loading an entire page from the <html> tag on down into an element of another page is going to result in some sort of Frankenstein monster of a DOM, if a browser will do it at all. Generally, when you use “.load()” to grab fragments of content to update a page, your server should respond with a piece of a page, not the whole thing. The jQuery deal with allowing a selector after the actual URL is intended to let you strip out a chunk of a page, which is really cool, but it has that drawback that the scripts won’t be executed in that case.

Answer by Starx

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!