How to implement JavaScript dynamic loading CSS and JS file _javascript skills

Source: Internet
Author: User

The project needs to use dynamic loading CSS files, sorted out, and by the way the dynamic loading JS function written an object, first code:

var dynamicloading = {
  css:function (path) {
 if (!path | | | path.length = = 0) {
  throw new Error (' argument ' path "I s required! ');
 }
 var head = document.getElementsByTagName (' head ') [0];
    var link = document.createelement (' link ');
    Link.href = path;
    Link.rel = ' stylesheet ';
    Link.type = ' text/css ';
    Head.appendchild (link);
  },
  js:function (path) {
 if (!path | | path.length = = 0) {
  throw new Error (' Argument "path" is required! ');
 var head = document.getElementsByTagName (' head ') [0];
    var script = document.createelement (' script ');
    SCRIPT.SRC = path;
    Script.type = ' text/javascript ';
    Head.appendchild (script);
  }


object contains two completely independent methods, which are used to load CSS files and JS files, parameters are the file path to load. The principle is very simple: create different nodes for different load file types, then add the respective attributes, and finally throw them into the head tag. After testing, this method is compatible with each browser, safe, non-toxic, environmental protection, is the web developer work standing code.
Here is the calling code, which is exceptionally simple:

Dynamically loading CSS file
dynamicloading.css ("Test.css");

Dynamically loading JS file
dynamicloading.js ("Test.js");

The above is to tell you how to implement JavaScript dynamic loading CSS and JS files, I hope to help you learn.

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.