避免 document.write()

Avoid document.write()

我已经使用 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。谢谢!

推荐: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。但是,如 link 中所述,当在不使用 <script> 标签的情况下插入脚本时,这会使您的站点容易受到脚本执行的攻击。

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

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 += '<img alt="Some text">';
<p>I was here first!</p>

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