2012-05-11 87 views
-3

可能重複:
How to dynamically insert a <script> tag via jQuery after page load?添加腳本到head標籤

我有這樣的代碼

var scri = "<script type=\"text/javascript\">var _gaq = _gaq || []; _gaq.push(['setAccount','UA-22xxxxx3-15']); _gax.push(['_trackPageview']); <\/script>"; 
document.getElementsByTagName("script")[23].add(scri); 
console.log(scri); 

我想該元素附加到的頭文檔和我嘗試.append().text().add()和很多其他方法,但我總是erros。最後一個是

Uncaught TypeError: Object #<HTMLScriptElement> has no method 'add' 

任何想法我怎麼能追加到頭元素?

+0

你所鏈接的jQuery庫? – Chase

+0

http://stackoverflow.com/questions/3857874/how-to-dynamically-insert-a-script-tag-via-jquery-after-page-load – PeeHaa

回答

3

你應該使用document.createElement.appendChild()

var script = document.createElement("script"); 
script.innerHTML = "alert(\"This is the truth.\");"; 
document.head.appendChild(script); 
+0

謝謝你的幫助。 – Leon

+0

爲什麼要將內聯代碼插入HEAD標籤?我知道這是OP所要求的,但沒有理由這樣做 - 也可以只執行所需的代碼,而不是將其插入到頭標籤中。 – jfriend00

+0

@ jfriend00你可能有更好的方法來做到這一點,但我認爲如果你有一個函數,你將不得不多次調用它,將它附加到DOM使得它更容易。另外,我想指出'document.head'的處理速度比'document.getElementsByTagName'head''[0]'快得多',並且即使在IE上也支持。 [自己測試](http://jsperf.com/document-head) –

0

你爲什麼要追加一個內嵌腳本HEAD標記?沒有必要這樣做。如果您想通過URL加載遠程腳本文件,但是在您的情況下不需要或不需要,追加到HEAD標記是非常有用的。

要就在您的JS代碼要運行該點執行一些行內代碼,只需執行你這樣的代碼:

var _gaq = _gaq || []; 
_gaq.push(['setAccount','UA-22xxxxx3-15']); 
_gaq.push(['_trackPageview']); 
相關問題