During Web development, you may encounter this situation: we need to reference functions in another js file through one js file, however, is there a way for another function to load data through the <script> tag on the page. Therefore, we have the need to dynamically load js files through js. The following provides a solution.
The method is relatively simple. For details about the instance, see the code:
File 1: demo. js
function demo(){alert("demo");}
File 2: test. js
function test(){alert("test");} function loadDemo(){var iHead = document.getElementsByTagName('HEAD').item(0); var iScript= document.createElement("script"); iScript.type = "text/javascript"; iScript.src="demo.js"; iHead.appendChild(iScript); }
File 3: test.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
Put the preceding 3 files in the same directory. The running result is that the js functions in the demo. js file can be dynamically loaded using the loadDemo () function in test. js in test.html.