Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>.

like image 498
Lai Yu-Hsuan Avatar asked Jun 08 '11 04:06

Lai Yu-Hsuan


People also ask

How do I ensure Javascript is loaded?

What is the best way to make sure javascript is running when page is fully loaded? If you mean "fully loaded" literally, i.e., all images and other resources downloaded, then you have to use an onload handler, e.g.: window. onload = function() { // Everything has loaded, so put your code here };

How jQuery load works?

The jQuery load() method is a simple, but powerful AJAX method. The load() method loads data from a server and puts the returned data into the selected element.

What does load function do in Javascript?

load() . The load() method attaches an event handler to the load event. The load event occurs when a specified element has been loaded. This event works with elements associated with a URL (image, script, frame, iframe), and the window object.

What is script async defer?

Async - means execute code when it is downloaded and do not block DOM construction during downloading process. Defer - means execute code after it's downloaded and browser finished DOM construction and rendering process.


1 Answers

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.

like image 162
Pointy Avatar answered Oct 11 '22 13:10

Pointy