Javascript Advanced Programming When talking about errors in IE, the concept of operation shorted is mentioned:
An error will occur when modifying a page that has not been loaded.
The sample code is:
<body>
<p></p>
<p>
<script>
document.body.appendChild(document.createElement("p"));
</script>
</p>
</body>
When <script> is included in an element and the JS code uses DOM methods to modify its parent element or ancestor element, an operation abort error will occur (because only elements that have been loaded can be modified).
was changed to
document.body.insertChild(document.createElement("p"),document.body.firstChild);
can avoid errors.
If the new <p> is added to the beginning of document.body instead of the end, there will be no error.
After reading it, I don’t quite understand how the document is loaded. Why does it work if it is inserted at the beginning of the body, but not at the end.
When the browser loads the page, it will load and parse the js code. At this time, it will stop parsing and rendering of other codes. This is why we generally put js code at the end of the page. It does not organize the loading of the page document structure and can operate on all DOM elements.
In the above code, when the js code is executed, the html structure of the entire page has not been loaded, so the browser does not know the end position of the body, and the beginning position of the body has been determined, so the new p can be added to the beginning. Cannot be added to the end.
Steps to load DOM document
1 Parse the HTML structure.
2 Load external scripts and stylesheet files.
3 Parse and execute script code.
4 Construct HTML DOM model. //DOMContentLoaded
5 loads external files such as images.
6 The page is loaded. //load
This is theoretically true, but in practice, the location of the document content must also be considered. Since it is parsed from top to bottom, when encountering js, it will block rendering for js parsing and execution.
The problem you mentioned, I guess is caused by the fact that the front part of the body has been rendered, but the tail part has not been rendered during execution, that is, I don’t know where to insert the tail part.
Due to the optimization of DOM operations in modern browsers, I can’t find any errors in testing on chrome. Both methods are fine, so there is no need to pay too much attention to this issue. Just remember to render sequentially and put js at the bottom.