Search code examples
javascriptpagespeeddocument.write

Avoid document.write()


I have tested my website with PageSpeed Insights and i have the following error: Avoid document.write(). I have on my website a javascript code used for tracking visitors:

    <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>

How can i replace document.write in this code. Thank you!


Solution

  • Recommended: Element.append()

    You can create an element using document.createElement(). That element can then be appended to 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

    You can add the String directly to the HTML using Element.innerHTML. However, as mentioned in the link, that makes your site vulnerable to script-execution when a script is inserted without using the <script>-tag.

    Example of the vulnerability (hover over the image-element to see its effect):

    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 + '">';

    But if you are sure that the string you build is safe, you can add the contained element like this (replace the String-placeholder below with your String):

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