How to dynamically load scripts and styles using JavaScript _ javascript skills

Source: Internet
Author: User
This article describes how to dynamically load scripts and styles in JavaScript. For more information, see A dynamic script

When the demand for websites increases, the demand for scripts gradually increases. We have to introduce too many JS scripts to reduce the performance of the entire site;
Therefore, the concept of dynamic scripts is introduced, and corresponding scripts are loaded at the right time;

1. dynamically introduce js files

Var flag = true; if (flag) {loadScript ('browserdetect. js '); // call the function and introduce the path;} function loadScript (url) {var script = document. createElement ('script'); // create a script tag; script. type = 'text/javascript '; // set the type attribute; script. src = url; // introduce url; document. getElementsByTagName ('head') [0]. appendChild (script); // introduce the scriptMedium ;}

2. dynamically execute js Code

Var script = document. createElement ('script'); script. type = 'text/javascript '; var text = document. createTextNode ("alert ('lil')"); // sets the script TAG content; IE reports an error; script. appendChild (text); document. getElementsByTagName ('head') [0]. appendChild (script); // PS: the IE browser considers the script as a special element and cannot access subnodes. // for compatibility, the text attribute can be used instead. function loadScriptString (code) {var script = document. createElement ("script"); script. type = "text/javascript"; try {// The IE browser considers the script as a special element and cannot access subnodes. An error is returned. script. appendChild (document. createTextNode (code); // W3C method;} catch (ex) {script. text = code; // IE Method;} document. body. appendChild (script) ;}// call; loadScriptString ("function sayHi () {alert ('Hi ')}");

2. Dynamic Style

To dynamically load style sheets, such as switching the website skin;
There are two ways to load styles, one is Tag, one is

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.