使用document.write动态添加脚本标记 [英] adding a script tag dynamically with document.write
问题描述
我不知道这是否是一个好主意,但我正尝试在我的HTML文档中添加一个使用document.write的脚本,仅在浏览器处于联机状态时才添加脚本。
< script>
var online = navigator.onLine;
if(online){
document.write(< script src ='。/ api.js'>< / script>);
}
< / script>
事情是浏览器在第一次关闭时停止< / script> ;
标签位于document.write函数中,导致其他所有内容被解释为HTML();
在html中出现重新排序),我知道我做错了什么,但想知道什么 解决方案
编辑:请参阅此主题和答案: https://stackoverflow.com/a/8024286/2192152
以下是我用于个人网站的代码:
/ * ****** ************************************************** *****
*加载任何js文件
******************************* ******************************* * /
staticPath ='。/ js /';
vendorPath ='。/ js / vendor /';
src = [
{f:'jquery-1.8.3.min.js',n:1},
{f:'jquery-ui-1.9.2.js',n:1},
{f:'li b.js',n:0},
];
for(var i in src)
{
if(src [i] .n === 0)document.write('<'+ 'script type =text / javascriptsrc ='+ staticPath + src [i] .f +'>< / sc'+'ript>');
else document.write('<'+'script type =text / javascriptsrc ='+ vendorPath + src [i] .f +'>< / sc'+'ript> );
$ / code>
正如你所看到的,你应该拆分包含脚本调用的字符串。我不知道为什么这是必要的更多。
注意:我尝试了很多设置,我在这里提供给您的是负载方面最快的一个时间(使用chrome)
I dont know if this is a good idea but I am trying to add a script using document.write in my HTML document that would add a script only if the browser is online.
<script>
var online = navigator.onLine;
if(online){
document.write("<script src='./api.js'></script>");
}
</script>
the thing is the browser is stoping at the first closing </script>
tag that is inside the document.write function, causing everything else to be interpreted as HTML ( ");
appears renedered in the html) , I know that I am doing something wrong but would like to know what
EDIT: please see this thread and answers: https://stackoverflow.com/a/8024286/2192152
Here is a code I used for a personal website:
/* *************************************************************
* Loading any js file.
************************************************************** */
staticPath ='./js/';
vendorPath='./js/vendor/';
src = [
{f:'jquery-1.8.3.min.js', n:1},
{f:'jquery-ui-1.9.2.js', n:1},
{f:'lib.js', n:0},
];
for (var i in src)
{
if (src[i].n === 0) document.write('<' + 'script type="text/javascript" src="' + staticPath + src[i].f + '"></sc' + 'ript>');
else document.write('<' + 'script type="text/javascript" src="' + vendorPath + src[i].f + '"></sc' + 'ript>');
}
As you can see you should split the string containing you script call. I unfortunately don't know much more of why this is needed.
Note: I tried many setting and the one I provide you here is the fastest one in terms of load time (using chrome)
这篇关于使用document.write动态添加脚本标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!