【问题标题】:Avoid document.write()避免 document.write()
【发布时间】:2022-04-11 21:36:16
【问题描述】:

我已使用 PageSpeed Insights 测试了我的网站,但出现以下错误:避免使用 document.write()。我的网站上有一个用于跟踪访问者的 javascript 代码:

    <script type="text/javascript" async>
document.write('<img src=\"https://traficwebsite/button.php?u=user&ref='+escape(document.referrer)+'&page='+escape(location.href.replace(/#.+$/,''))+'&rez='+screen.width+'x'+screen.height+'\" alt=\"DespreTrafic\" border=\"0\" width=\"1\" height=\"1\" />');
</script>

如何在这段代码中替换 document.write。谢谢!

【问题讨论】:

标签: javascript pagespeed document.write


【解决方案1】:

推荐:Element.append()

您可以使用document.createElement() 创建元素。 然后可以将该元素附加到document.body

// Create an <img>-element
var img = document.createElement('img');

// Configure the attributes of your element
img.alt = 'An alternative text';

// Append it
document.body.append(img);

Element.innerHTML

您可以使用Element.innerHTML 将字符串直接添加到HTML。但是,如链接中所述,当插入脚本而不使用 &lt;script&gt;-tag 时,这会使您的网站容易受到脚本执行的影响。

漏洞示例(将鼠标悬停在图像元素上以查看其效果):

var altText = 'some text" onmouseover="(() => {console.log(\'This lambda was executed!\')})()';

// This will add the following:
// <img alt="some text" onmouseover="(() => {console.log('This lambda was executed!')})()">
document.body.innerHTML += '<img alt="' + altText + '">';

但是如果你确定你构建的字符串是安全的,你可以像这样添加包含的元素(用你的字符串替换下面的字符串占位符):

document.body.innerHTML += '&lt;img alt="Some text"&gt;';
&lt;p&gt;I was here first!&lt;/p&gt;

【讨论】:

    【解决方案2】:

    我不推荐 Element.innerHTML。 编辑 Element.innerHTML 会将一些给定的事件删除到元素(例如 VueJs 应用程序)。最好使用 document.body.append。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 2011-11-19
      • 2018-01-11
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多