2

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!

A. Marian
  • 55
  • 8
  • 4
    Does this answer your question? [Programmatically change the src of an img tag](https://stackoverflow.com/questions/11722400/programmatically-change-the-src-of-an-img-tag) – Peter B Dec 08 '20 at 11:11
  • Does this answer your question? [Avoid using document.write() occurs when trying to load a dashboard page in Chrome](https://stackoverflow.com/questions/48736040/avoid-using-document-write-occurs-when-trying-to-load-a-dashboard-page-in-chro) – Yasmin Dec 08 '20 at 11:15
  • it does not matter if you declare your script as async, document write is still blocking. It is bad practice to use it and both chrome and firefox will throw errors / warning upon evaluating it. You are not doing your users a favour neither since your code will be slow to execute, assuming you get it to work – rags2riches-prog Dec 08 '20 at 11:17

2 Answers2

2

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>
Oskar Grosser
  • 2,804
  • 1
  • 7
  • 18
0

I do not recommend Element.innerHTML. Editing Element.innerHTML removes some of the given events to elements (e.g. the VueJs application). Better to use document.body.append.

PLI52KA
  • 11
  • 3