How does form value caching work in browsers?

2019-07-15 06:41发布

I've read somewhere in a documentation that most browsers don't update DOM as form values change, because frequent DOM manipulation need heavy computing performance. Instead, they create a cache of form values to register form manipulation, and only update the DOM when a the form is submitted.

Do browsers really work this way? Is there an extensive documentation about this behavior?

1条回答
唯我独甜
2楼-- · 2019-07-15 07:28

DOM elements have properties and attributes.

If you change an attribute e.g. the value="" then the DOM is changed.
But the current value of a form element is stored in the property value and this is the one that is changed when the user types something e.g. into an input field.

If the attribute changes the css rules needs to be rechecked if some don't apply anymore or some others will apply now.

Here a little example:

CSS

[value='foo'] {
    color: red;
}

[value='bar'] {
    color: green;
}

HTML

<input id="text-element" type="text" value="foo"><br>

<a href="#" id="prop-change">prop-change</a>
<a href="#" id="attr-change">attr-change</a>

JS

document.getElementById("attr-change").onclick = function() {
    document.getElementById("text-element").setAttribute("value","bar");
    return false;
};

document.getElementById("prop-change").onclick  = function(e) {
    document.getElementById("text-element").value = "bar";
    return false;
};

Live Demo (JSFiddle)

If you try this in current FireFox or Chrome and type bar or click on prop-change the color is not changing to green.

But if you click on attr-change it turns green because the attribute changes.

Additionally if you reload and type e.g. test into it and then press attr-change you see that it will turn green but test will still be the current value.

查看更多
登录 后发表回答