1. 引言
在上一篇文章《如何确保JavaScript的执行顺序 – 之jQuery.html深度分析》中,我们揭示了jQuery.html函数之所以能在各种浏览器下保持动态JS顺序执行,其秘密在于 – 同步AJAX获取外部JavaScript。
我们先来简单回顾下HTML源代码(test2.htm):
<html>
<head>
<title></title>
<script src=”js/jquery-1.4.4.js” type=”text/javascript”></script>
<script>
$(function(){
$(‘#container’).html(‘<script src=”./service.ashx?file=js/jquery-ui.js&delay=2000″ type=”text/javascript”></script>’ + ‘<script>alert(typeof(jQuery.ui));</script>’);
});
</script>
</head>
<body>
<div id=”container”>
</div>
</body>
</html>
顺便一提的是,通过这种方式加载的外部JavaScript不可以在Firebug中调试,因为AJAX结束后外部JavaScript的解析和内联JavaScript的解析是一样的(都是调用jQuery.globalEval):

下面进入本篇文章的主题:如果加载的JS是在其它域下面的,jQuery.html还能在各个浏览器下都能保证JS的顺序执行么?
2. 建立测试案例
1) 准备两个域名
为了测试,我在个人主页(http://sanshi.me/)下面临时创建了两个子域名,分别是:
http://test.sanshi.me/
http://test1.sanshi.me/
2) 更新Demo页面(test2_1.htm)
我会把test2_1.htm放在第一个子域名下,访问地址为http://test.sanshi.me/jsorder/test2_1.htm,其源代码如下:
<html>
<head>
<title></title>
<script src=”js/jquery-1.4.4.js” type=”text/javascript”></script>
<script>
$(function () {
$(‘#container’).html(‘<script src=”http://test1.sanshi.me/jsorder/service.ashx?file=js/jquery-ui.js&delay=2000″ type=”text/javascript”></script>’ + ‘<script>alert(typeof(jQuery.ui));</script>’);
});
</script>
</head>
<body>
<div id=”container”>
</div>
</body>
</html>
可以看到,其中的jQueryUI脚本指向的是第二个域名下的(test1.sanshi.me)。
3) 在不同浏览器下测试










