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

How to Dynamically Inject Script Tags with Dynamic Sources Containing `document.write`?

Patricia Arquette
Release: 2024-10-30 02:26:02
Original
946 people have browsed it

How to Dynamically Inject Script Tags with Dynamic Sources Containing `document.write`?

Dynamic Script Tag Injection with Dynamic Source

When attempting to dynamically add a script tag to a webpage, it is important to consider potential issues with the source of the script, such as its inclusion of document.write. While traditional methods of script injection work well for scripts with static sources, they can fail in these cases.

To effectively inject a script tag with a dynamically generated source that may include document.write, a different approach is required. This involves creating a new script element using document.createElement('script'), setting its src attribute to the desired source, and appending it to the document.head.

For instance, the following code demonstrates how to dynamically add a script tag with a source that includes document.write:

var my_awesome_script = document.createElement('script');

my_awesome_script.setAttribute('src','http://example.com/site.js');

document.head.appendChild(my_awesome_script);
Copy after login

By using this method, the browser will execute the script code dynamically, including any document.write calls it contains. This provides a reliable and effective way to inject scripts with dynamic sources.

The above is the detailed content of How to Dynamically Inject Script Tags with Dynamic Sources Containing `document.write`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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