Home > Web Front-end > JS Tutorial > How to Dynamically Include External Scripts with Variable URLs that Contain `document.write` Commands?

How to Dynamically Include External Scripts with Variable URLs that Contain `document.write` Commands?

Barbara Streisand
Release: 2024-11-02 20:50:02
Original
627 people have browsed it

How to Dynamically Include External Scripts with Variable URLs that Contain `document.write` Commands?

Including External Scripts Dynamically with Variable URLs

When dynamically adding script tags to a webpage, it's essential to consider scripts with src attributes that may include document.write commands. This can disrupt the normal loading behavior.

The Issue

In ordinary scenarios, using the following code to include a script from "source.js" works well:

<script type="text/javascript" src="source.js"></script>
Copy after login

However, "source.js" may contain the following unusual content:

document.write('<script type="text/javascript">')
document.write('alert("hello world")')
document.write('</script>')
document.write('<p>goodbye world</p>')
Copy after login

The Solution

Using the ordinary method will not handle this scenario correctly. Instead, you can use the following technique to dynamically add scripts with variable srcs:

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

This method creates a new script element, sets its src attribute, and appends it to the of the document. It works even if the script's src includes document.write commands.

The above is the detailed content of How to Dynamically Include External Scripts with Variable URLs that Contain `document.write` Commands?. 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