简体   繁体   English

使用document.write动态添加脚本标签

[英]adding a script tag dynamically with document.write

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. 我不知道这是否是个好主意,但我尝试在HTML文档中使用document.write添加脚本,该脚本仅在浏览器在线时才会添加脚本。

<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 问题是浏览器在document.write函数内部的第一个</script>标记处停止,导致其他所有内容都解释为HTML( ");在html中重新显示,我知道我在做出了点问题,但想知道什么

EDIT: please see this thread and answers: https://stackoverflow.com/a/8024286/2192152 编辑:请参阅此线程和答案: 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) 注意:我尝试了许多设置,在加载时间方面,我为您提供的设置是最快的设置(使用chrome)

Try this: 尝试这个:

document.write("<script src='./api'></"+"script>");

You're right. 你是对的。 Browsers read all <script> ... </script> block and pass them to JS engine. 浏览器读取所有<script> ... </script>块,并将它们传递给JS引擎。 So, if you want to write </script> you should break it. 因此,如果您想编写</script> ,则应将其破坏。

Note Using document.write to add JavaScript to document is not a good idea. 注意使用document.write将JavaScript添加到文档不是一个好主意。

You could try: 您可以尝试:

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "./api.js";
document.head.appendChild(script);

also are you missing extension on api? 您还缺少api扩展吗? should it be api.js? 应该是api.js吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM