2011-02-27 99 views

回答

35
var head = document.getElementsByTagName('head')[0]; 
var script = document.createElement('script'); 
script.type = 'text/javascript'; 
script.onload = function() { 
    callFunctionFromScript(); 
} 
script.src = 'path/to/your-script.js'; 
head.appendChild(script); 
1
document.head.appendChild(document.createElement('script').setAttribute('src','http://ex.com/javascript.js')); 
+0

這不應該工作,因爲'setAttribute()'不返回元素:「返回值:\t沒有返回值」https:// www。 w3schools.com/jsref/met_element_setattribute.asp但是你可以把元素放入一個變量'element'中,然後調用'element.setAttribute(...)'和'appendChild(element)' – 2017-06-02 09:02:58

1

這裏是我在飛行中注入的功能沒有任何的源文件等

document.head.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}'); 

如果你在執行此之後注入到身體

document.body.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}'); 

試試LogIt('hello');你應該在控制檯上看到'hello'。

相關問題