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!