How to dynamically load js through JavaScript

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.