document.write动态加载脚本 [英] document.write loading scripts dynamically

查看:303
本文介绍了document.write动态加载脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态加载脚本。这是我的代码:

  document.write('< script type =text / javascript> window.jQuery | | document.write(\< script src = \'http://code.jquery.com/jquery-1.10.2.min.js\'>< / script> \)< ; /脚本>'); 

这是B.js中的内容,它以A.html的脚本形式加载。但我得到错误。



任何想法如何解决这个问题?


在JavaScript字符串文字中将< / 表示为< \ / b
$ b

转义 / 对于JavaScript解析器保持相同的含义,但不适用于HTML解析器。



由于您的HTML包含JavaScript,其中包含包含HTML(?)的JavaScript的HTML,因此您必须加倍逃避最内层的HTML。 p>

我认为这会起作用:

  document.write('< script type =text / javascript> window.jQuery || document.write(\< script src = \'http://code.jquery.com/jquery-1.10.2.min.js\\ \\ '>< \\ /脚本> \)< \ /脚本>'); 

...但这太可怕了,似乎没有什么意义要生成一个新的脚本元素来决定如果你想要生成一个新的脚本元素。你会得到相同的结果:

  if(!window.jQuery){
document.write(< ; script src ='http://code.jquery.com/jquery-1.10.2.min.js'>< \ / script>;
}


I am trying to load script dynamically. This is my code:

document.write('<script type="text/javascript">window.jQuery || document.write(\"<script src=\'http://code.jquery.com/jquery-1.10.2.min.js\'></script>\")</script>');

This is inside B.js which is loaded as script on A.html. But I get error. The end script tag inside double quotes is treated as if it's nested script tag and breaking the code.

Any ideas how to fix this?

解决方案

Represent </ inside a JavaScript string literal as <\/.

Escaping the / keeps the meaning the same for the JavaScript parser but not for the HTML parser.

Since you have HTML containing JavaScript containing HTML containing JavaScript containing HTML (!!!) you have to double escape the inner most ones.

I think this will work:

document.write('<script type="text/javascript">window.jQuery || document.write(\"<script src=\'http://code.jquery.com/jquery-1.10.2.min.js\'><\\/script>\")<\/script>');

… but it is horrible and there seems to be little point in generating a new script element just to decide if you want to generate a new script element though. You would get the same result with:

if (!window.jQuery) {
  document.write("<script src='http://code.jquery.com/jquery-1.10.2.min.js'><\/script>";
}

这篇关于document.write动态加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆