Home  >  Article  >  Web Front-end  >  How to Dynamically Inject Script Tags with Dynamic Sources Containing `document.write`?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 02:26:02893browse

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);

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!

Statement:
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