Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a click setting innerHTML trigger two parsing events on Chrome?

Using the Timeline in the Chrome Developer Tools, I used this small piece of code to record events through innerHTML :

<!DOCTYPE html>

<html>
<head>
  <script>
    function test(){
      var wrap = document.getElementById('wrapper');
      wrap.innerHTML = "test";
    }
  </script>
</head>

<body>
  <input type="button" value="click" onClick="test();"/>
  <div id="wrapper"></div>
</body>
</html>

And I can see that there are two parsing events fired once the test method is run :

Chrome Timeline showing parsing double events

I am using Chrome Version 23.0.1271.64 m

Is it something expected ? Is it a bug from the Chrome Developer Tools ? or is there something to improve under Chrome ?

like image 981
JBE Avatar asked Nov 11 '12 22:11

JBE


People also ask

Why innerHTML does not work?

People can struggle and complain about innerHTML not working. Such things usually occur because of human error, when strings are not appropriately defined, or there are some mistakes in JavaScript code.

Should I avoid innerHTML?

The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies. You can read the MDN documentation on innerHTML .

What can I use instead of innerHTML?

replaceChildren() is a convenient alternative to innerHTML and append() append() appends nodes to the parent node.

What does innerHTML do?

The innerHTML property is part of the Document Object Model (DOM) that allows Javascript code to manipulate a website being displayed. Specifically, it allows reading and replacing everything within a given DOM element (HTML tag).


1 Answers

After a bit of playing around I would guess that this has something to do with Chrome needing to parse the string "test" and then re-parse the page, or possibly just the "wrap" element after the string has been added. innerHTML is a curious function because it allows the addition of any content whatsoever, so some validation/parsing has to occur.

It is somewhat telling that if you change your function to this :

function test() {
    var wrap = document.getElementById('wrapper');
    var newtext = document.createTextNode("test");
    wrap.appendChild(newtext);
}

...then no parse events occur at all.

like image 55
adhocgeek Avatar answered Oct 14 '22 12:10

adhocgeek