想在不阻塞頁面的情況下載入外部腳本?利用 iframe 是一種可行的思路。不過要注意,透過異步請求取得的 script 內容並不會自動執行,因為返回的文字並未經過瀏覽器解析執行。以下用兩個頁面的互動來示範。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>無標題頁</title>
</head>
<script type="text/javascript">
function testClick()
{
document.getElementById("tsrc").src = "a2.html"
}
</script>
<body>
<div style="display:none"><iframe id="tsrc"></iframe></div>
<input id="Button1" type="button" value="異步加載script" onclick="testClick()"/>
</body>
</html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>無標題頁</title>
</head>
<body>
<script>
alert('我是異步script');
</script>
</body>
</html>
主頁面裡藏了一個隱藏的 iframe(id 為 tsrc),當使用者點擊按鈕觸發 testClick() 時,程式把 iframe 的 src 設為 a2.html。瀏覽器載入這個 iframe 頁面時,會正常解析並執行其中的 <script>,於是便彈出「我是異步script」的提示。
這種做法的巧妙之處在於:藉由 iframe 這個天然的「腳本執行環境」,把外部腳本的載入與執行交給瀏覽器自行處理,而主頁面則完全不必阻塞等待。這與直接用 Ajax 抓取腳本文字再 eval 的方式相比,顯得更為簡潔可靠。