用下面的 include 函式動態插入 script 標籤,跨網域載入 jQuery:
function include(path){
var a = document.createElement("script");
a.type = "text/javascript";
a.src = path;
var head = document.getElementsByTagName("head")[0];
head.appendChild(a);
}
include("https://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js");
這個寫法在 IE8 下會遇到一個惱人的狀況:在網址列按 Enter 開啟頁面時,jQuery 的物件與方法都能正常使用;但一按重新整理,jQuery 就失效了,非得再去網址列敲一次 Enter 才會恢復。同樣的程式碼在 Firefox 下完全正常。
問題根源在於動態插入的外部腳本並不會被瀏覽器等待,IE8 在重新整理的流程裡往往先執行到依賴 jQuery 的程式碼,腳本還沒就位。
下面附上一個可測試 window.name 跨域取值的完整頁面,用 iframe 兩段式載入加上同源中介頁 none.html 的做法,繞開同源政策限制:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>Demo:跨域</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function include(path){
var a = document.createElement("script");
a.type = "text/javascript";
a.src = path;
var head = document.getElementsByTagName("head")[0];
head.appendChild(a);
}
include("https://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js")
</script>
<script>
$(function(){
function sendData(url, callback){
if(!url || typeof url !== 'string'){
return;
}
url += (url.indexOf('?') > 0 ? '&' : '?') + 'windowname=true';
var frame = $('<iframe style="display:none;"></iframe>').appendTo("body");
var state = 0;
var clear = function(){
try{
frame[0].contentWindow.document.write('');//清空 iframe 內容
frame[0].contentWindow.close();//避免 iframe 記憶體洩漏
frame.remove();//刪除 iframe
}catch(e){}
};
var getData = function(){
try{
var data = frame[0].contentWindow.name;
}catch(e){}
clear();
if(callback && typeof callback === 'function'){
callback(data);
}
};
frame.bind('load', function(){
if(state === 1){
getData();
} else if(state === 0){
state = 1;
frame[0].contentWindow.location = "none.html";
}
});
frame[0].src = url;
}
// 應用
var testurl = 'https://www.jb51.cn/test.html';
$("button").click(function(){
sendData( testurl ,function(result){
var fishDiv = $("#oldFish");
fishDiv.html( "你獲取的數據是:"+result );
})
})
})
</script>
</head>
<body>
<button>遠程加載數據</button>
<div id="oldFish"></div>
<p style="font-size:12px;">Dev By <a href="https://www.jb51.cn" >素材下載</a> & 桦</p>
</body>
</html>
如果目標只是讓動態載入的 jQuery 在 IE8 下穩定可用,比較可靠的做法是改用 onreadystatechange 搭配 onload 等待腳本真正就位後,再執行依賴它的程式碼,而不是急著在下一行呼叫。