Home > Article > Web Front-end > JavaScript Advanced (2) Referencing another JS file in one JS file
Method 1
Add the following example code at the top of the calling file:
document.write(”<script language=javascript src='js/import.js’></script>”);
(Note: Sometimes the files you reference may also need to reference other js, we need to reference the required js file in the same way)
Applying js through the intermediate interface means that we can reference the js file you need in a certain html. We can get the object of that html file, and then use this object to reference the js method.
Put the following code into the Body:
new_element=document.createElement(”script”); new_element.setAttribute(”type”,”text/javascript”); new_element.setAttribute(”src”,”import.js”); document.body.appendChild(new_element);
Let’s analyze it Here are a few key lines of code:
First, we use document.createElement("script") to generate a script tag, set its type attribute to text/javascript, and src to import.js (1 here) .js and 2.js are placed in the same directory, or they can be placed in different directories). Finally, this tag is dynamically added to the body. In this way, we can call methods in different js files.
Note: c16f708ea1d24dfc75ce4a52e73adfcc2cacc6d41bbb37262a98f745aa00fbf0 must be placed under the body. Because body (document.body.appendChild(new_element);) is used in 2.js. If you put the code such as 2.js on the body, that is to say, after entering the page, b has been executed before the body is generated. document.body.appendChild(new_element); in .js. At this time, a JavaScript error will be thrown if the body does not exist.
The above is the content of JavaScript Advanced (2) referencing another JS file in one JS file. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!