为什么使用 document.write 需要将</script>拆分开?指南教程_script使用帮助

细心点的朋友可能会注意到,有些网站使用document.write动态加载JS的时候需要把拆分开来写?如下面的例子所示:if (typeof window[‘jQuery’] == ‘undefined’) document.write(‘<scr'+'ipt type="tex

为什么使用 document.write 需要将</script>拆分开?指南教程

细心点的朋友可能会注意到,有些网站使用document.write动态加载JS的时候需要把</script>拆分开来写?如下面的例子所示:

为什么使用 document.write 需要将</script>拆分开?指南教程_script使用帮助

<script type='text/javascript'>
  if (typeof window['jQuery'] == 'undefined') document.write('<scr'+'ipt type="text/javascript" src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></sc'+'ript>');
</script>

为此,我们可以做一个实验,打开记事本填入下面的内容,另存为html格式,使用浏览器打开看看:

<html>
<body>
<script type="text/javascript">
    document.write('<script type="text/javascript">alert(1024);</script>');
    alert(2048)
</script>
</body>
</html>

最后你会发现结果是这样的:

'); alert(2048)

因此,我们可以猜出原因可能是,</script> 如果不拆开,会导致过早结束script块,导致后面的JS都被解析成了普通的文本。

扩展一下,提供另外一种方法在纯JS中动态加载脚本:

if (typeof(jQuery) == 'undefined') {
    (function() {
        var sct = document.createElement('script');
        sct.src = ('https:' == document.location.protocol ? 'https' : 'http') +
          '://cdn.bootcss.com/jquery/3.4.1/jquery.js';
        sct.type = 'text/javascript';
        var myjs = document.getElementsByTagName('script')[0];
        myjs.parentNode.insertBefore(sct, myjs);
    })();
}
海计划公众号
(0)
上一篇 2020/03/23 01:37
下一篇 2020/03/23 01:37

您可能感兴趣的内容