2013-07-07 100 views
2

我有下面的js。這也是this fiddle用js創建js文件的鏈接

(function() { 
     var test = document.createElement('script'); 
     test.type = 'text/javascript'; 
     test.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.example.com/test.js'; 
     console.log(test); 
     document.getElementsByTagName('body')[0].insertAdjacentHTML("beforeEnd", test); 
    })(); 

我想在結束JS代碼前把JS在我的頁面的底部。

當我在console.log中查看它時,我得到了預期的結果。 這是

<script type=​"text/​javascript" src=​"http:​/​/​www.example.com/​test.js">​</script>​ 

然而,當我嘗試,實際上它添加到我的網頁,我得到[對象HTMLScriptElement]

缺少什麼我在這裏還是有另一種方法,我可以嘗試達致這?

回答

4

insertAdjacentHTML以html爲參數而不是dom節點。我會使用appendChild來代替

document.getElementsByTagName('body')[0].appendChild(test); 
+0

'appendChild'還具有通用瀏覽器支持的好處,而insertAdjacentHTML不是這種情況。 – Yahel

2

我採取了一種稍微不同的方法,並嘗試將該腳本附加爲主體節點的子節點。這裏有一個使用你的代碼的例子:

(function (document) { 
    var test = document.createElement('script'); 
    test.type = 'text/javascript'; 
    test.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.example.com/test.js'; 
    document.getElementsByTagName('body')[0].appendChild(test); 
})(document); 

它似乎得到了預期的結果。

希望這會有所幫助!