如果腳本標記已經存在,則可以將其text
/ textContent
/ innerText
值設置為要執行的任何代碼。 但是腳本需要事先為空,即沒有文本,甚至沒有空格,否則它將無法運行。
//use an appropriate css selector to find the correct script
//this just selects the first script it finds
var s = document.querySelector('script');
s.text = 'alert("Here")';
最好只創建一個新的script元素並向其中添加代碼,因為那樣您就不必擔心是否已經使用過script標簽了。
var s = document.createElement('script');
document.head.appendChild(s);
s.text = 'alert("Here")';
當然,如果腳本是使用src
屬性設置的,那么腳本的文本將不會運行任何代碼,因為外部鏈接的腳本元素會忽略該代碼。