JavaScript doesn't execute in Safari when load

2019-01-29 01:56发布

问题:

I have these two pages:

page1.html

http://vidasp.net/tinydemos/jquery-load-issue/page1.html

<!DOCTYPE html>

<html>
<body>
    <div id="wrap"> </div>

    <script src="jquery.js"></script>
    <script> $(function() { $('#wrap').load('page2.html'); }); </script>
</body>
</html>

page2.html

http://vidasp.net/tinydemos/jquery-load-issue/page2.html

<!DOCTYPE html>

<html>
<head>
    <script> alert('Page 2 HEAD'); </script>
</head>
<body>
    <p> PAGE 2 </p>
    <script> alert('Page 2 BODY'); </script>
</body>
</html>

As you can see, I am loading the entire page2.html into the #wrap element of page1.html. Notice, that page2.html contains two SCRIPT elements with alert() function calls - one in the HEAD of the page, and the other one in the BODY of the page.

The issue:

In Firefox 3.9, IE9 beta, Chrome (latest) and Opera 11, both alerts execute. In Safari 5, only the second alert executes.

Is this a Safari bug?

回答1:

Seems like this is a Safari issue, but maybe not a bug (and may happen in other browsers):

jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

http://api.jquery.com/load/

I'm guessing that applies to anytime .load() is used, not just when getting fragments. But I think it would be best, since you are pulling content into a <body> element that it not include a <head> tag?