在帖子How to load javascript code to an html fil中,有一种方法可以在运行时简单地加载外部js并执行。但是有两个问题:我们不知道它何时会被执行,我们无法自定义代码。
我正在使用此代码:
var elemScript=document.createElement('script');
elemScript.setAttribute('type', 'text/javascript');
elemScript.setAttribute('language', 'javascript');
var txt = document.createTextNode(result);
elemScript.appendChild(txt);
document.head.appendChild(elemScript);
在http请求中,其中result是由php提供的代码,为我生成自定义代码。上面我可以发送一些需要代码等的功能。
但是这种美在IE8或更老版本中不起作用。有没有办法让它发挥作用或者是时候忘记这些旧的航海家了?
有什么建议吗?
答案 0 :(得分:1)
编辑:最终解决方案:
IE8及以下版本不允许您使用innerHTML,innerText,appendChild(txtNode)或任何其他类型的DOM操作来修改脚本的代码。执行包含在字符串中的脚本的唯一方法是使用eval。以下代码已在chrome,firefox,safari,IE9,IE8和IE7中进行了测试。
(function (window, undefined) {
var loaded = false;
function onScriptLoaded() // executes after external script has loaded
{
if (loaded)
return;
// this flag is to prevent versions of ie that do support onload
// from executing this function twice
loaded = true;
// example javascript loaded from php file
var phpScriptText = "window.alert('This was added to external script using php');";
// this is the only way for this to work accross all browsers
window.eval.call(window, phpScriptText);
}
window.onload = function () { // load external script and execute onScriptLoaded when it's done loading
var doc = window.document;
var script = doc.createElement("script");
script.type = "text/javascript";
script.src = "externalScript.js";
script.async = true;
script.onload = onScriptLoaded; // works in most browsers
// for IE
if (script.onreadystatechange !== undefined) {
script.timer = setInterval(function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
onScriptLoaded();
clearInterval(script.timer);
}
}, 100);
}
doc.getElementsByTagName("head")[0].appendChild(script);
};
})(window);