且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

document.write动态加载脚本

更新时间:2023-12-04 23:38:46

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>";
}