[英]how to add a script value dynamically in html head tag in javascript
[英]How to add javascript file dynamically in the head of html?
從下面的代碼中,我試圖動態加載JavaScript文件TestJScript.js,並且在加載后要調用該文件中存在的javascript函數LoadData()。 但是我遇到錯誤,請檢查圖像。
注意:錯誤僅在IE-8.0.6001更新0上獲得。
請建議我進行更正,以使其能夠從6到IE的所有版本。 或任何其他解決方案。
如果需要任何Windows更新。 請告訴我。
請不要建議使用JQUERY代碼
Javascript文件代碼:
function LoadData() {
alert('ok');
}
碼:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function LoadJSFile() {
var js = document.createElement("script")
js.setAttribute("type", "text/javascript")
js.setAttribute("src", "C:\\TestJScript.js")
document.getElementsByTagName("head")[0].appendChild(js)
//call below function exist in TestJScript.js file
LoadData();
}
</script>
</head>
<body onload="LoadJSFile();">
</body>
</html>
錯誤圖片:
試試這個http://dustindiaz.com/scriptjs 。 像這樣:
$script('yui-base.js', function() {
// do stuff with base...
$script(['yui-anim.js', 'yui-connect.js'], function() {
// do stuff with anim and connect...
});
$script('yui-drag.js', function() {
// do stuff with drag...
});
});
該錯誤報告您正在加載的javascript文件中的問題。 因此,問題不在於如何動態加載javascript文件,而在於javascript文件本身。
文件加載后似乎存在問題。 您確定文件本身沒有語法錯誤。
另外,我建議您使用javascript文件的相對路徑,而不要使用絕對路徑。
編輯:
嘗試這個:
function LoadJSFile() {
var script = document.createElement('script');
script.src = "C:\\TestJScript.js";
script.onload = function () {
LoadData();
};
document.getElementsByTagName("head")[0].appendChild(script)
}
您可以嘗試以下方法:
<script>
function LoadJSFile(src, callback) {
var js = document.createElement('script');
js.src = src;
js.async = true;
js.onreadystatechange = js.onload = function() {
var state = js.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(js);
}
LoadJSFile('C:\\TestJScript.js', function() {
LoadData();
});
</script>
如果使用的是c#代碼,則另一個解決此腳本錯誤的方法是通過c#代碼調用腳本。 碼:
/
/Assiging html value to control
webBrowser.DocumentText = "HTML content";
//Calling document load completed event
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlDocument htmlDocument = webBrowser.Document;
HtmlElement htmlElementHead = htmlDocument.GetElementsByTagName("head")[0];
HtmlElement HtmlElementScript = htmlDocument.CreateElement("script");
HtmlElementScript.SetAttribute("text", "C:\\TestJScript.js");
htmlElementHead.AppendChild(HtmlElementScript);
htmlDocument.InvokeScript("LoadData");
webBrowser.DocumentCompleted -= webBrowser_DocumentCompleted;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.