首页 > 解决方案 > 避免 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。谢谢!

标签: javascriptpagespeeddocument.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);

元素.innerHTML

您可以使用 .将字符串直接添加到 HTML 中Element.innerHTML。但是,如链接中所述,当插入脚本而不使用<script>-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 += '<img alt="Some text">';
<p>I was here first!</p>


推荐阅读