通过jQuery的load()方法加载整个页面时,JavaScript不会在Safari中执行

时间:2011-01-24 21:38:36

标签: javascript jquery safari

我有这两页:

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>

如您所见,我将整个page2.html加载到page1.html的#wrap元素中。请注意,page2.html包含两个带有alert()函数调用的SCRIPT元素 - 一个位于页面的HEAD中,另一个位于页面的BODY中。

问题:

在Firefox 3.9,IE9 beta,Chrome(最新)和Opera 11中,两个警报都会执行。 在Safari 5中,仅执行第二个警报。

这是Safari的错误吗?

1 个答案:

答案 0 :(得分:4)

似乎这是Safari问题,但可能不是错误(可能会在其他浏览器中发生):

  

jQuery使用浏览器的.innerHTML属性来解析检索到的文档并将其插入到当前文档中。在此过程中,浏览器通常会过滤文档中的元素,例如<html>, <title>, or <head>元素。因此,.load()检索的元素可能与浏览器直接检索文档的内容不完全相同。

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

我猜这适用于任何时候使用.load(),而不仅仅是在获取片段时。但我认为这是最好的,因为您将内容添加到<body>元素中,但不包含<head>代码?