Home > Web Front-end > JS Tutorial > How to Override document.write() Limitations in Asynchronous Script Loading?

How to Override document.write() Limitations in Asynchronous Script Loading?

Patricia Arquette
Release: 2024-10-20 14:04:02
Original
511 people have browsed it

How to Override document.write() Limitations in Asynchronous Script Loading?

Asynchronous Script Loading: Understanding document.write() Limitations

When executing scripts asynchronously, after the initial page load, it's essential to be aware of the limitations it poses on document manipulation. As stated in the console message, "It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened."

This means that using document.write() within such externally loaded scripts won't effectively write to the document, even though the script itself loads successfully. The reason lies in the fact that asynchronous scripts run after the document has been parsed and closed.

To address this issue, it's necessary to substitute document.write() with explicit DOM manipulations. Instead of writing directly to the document, create the desired DOM elements and append them to the document using methods like appendChild(), insertBefore(), or by setting the innerHTML property.

For instance, instead of using document.write() in an inline script:

<div id="container">
<script>
document.write('<span style="color:red;">Hello</span>');
</script>
</div>
Copy after login

In a dynamically loaded script, replace it with the following:

var container = document.getElementById("container");
var content = document.createElement("span");
content.style.color = "red";
content.innerHTML = "Hello";
container.appendChild(content);
Copy after login

Alternatively, if there is no other content in the container, you can directly set the innerHTML property:

var container = document.getElementById("container");
container.innerHTML = '<span style="color:red;">Hello</span>';
Copy after login

By following these guidelines, you can effectively manipulate the DOM from asynchronously loaded scripts without encountering the "Failed to execute 'write' on 'Document'" error.

The above is the detailed content of How to Override document.write() Limitations in Asynchronous Script Loading?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template