Home > Web Front-end > JS Tutorial > body text

Why Can\'t You Execute Write on Documents with Asynchronously-Loaded Scripts?

Susan Sarandon
Release: 2024-10-20 14:10:02
Original
160 people have browsed it

Why Can't You Execute Write on Documents with Asynchronously-Loaded Scripts?

Execute write on doc: What's the Issue with Asynchronously-Loaded Scripts?

When working with asynchronously-loaded scripts, you may encounter the error "Failed to execute 'write' on document. It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened." This occurs because asynchronous scripts load after the document has been fully parsed and closed, making direct alterations to the DOM using functions like document.write() ineffective.

Understanding the Solution

To resolve this issue, you must replace document.write() with explicit DOM manipulations. Instead of relying on the automatic insertion of content, you need to manually create DOM elements and insert them appropriately.

Example

Consider the following inline script that inserts a red "Hello" text into a "container" div:

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

To perform the same action with an asynchronously-loaded script, you would replace the inline script with the following code:

<code class="javascript">var container = document.getElementById("container");
var content = document.createElement("span");
content.style.color = "red";
content.innerHTML = "Hello";
container.appendChild(content);</code>
Copy after login

Alternatively, if the container has no other content, you can simply overwrite its innerHTML:

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

By adopting explicit DOM manipulations, you can ensure that your asynchronously-loaded scripts interact with the document effectively, avoiding the limitations imposed by delayed script execution.

The above is the detailed content of Why Can\'t You Execute Write on Documents with Asynchronously-Loaded Scripts?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!