How to achieve JavaScript dynamic loading of CSS and JS files, javascriptcss

Source: Internet
Author: User

How to achieve JavaScript dynamic loading of CSS and JS files, javascriptcss

The project needs to use the dynamic loading of CSS files. After sorting it out, the function of dynamic loading of JS is integrated into an object, first go to the Code:

var dynamicLoading = {  css: function(path){ if(!path || path.length === 0){  throw new Error('argument "path" is 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);  }}

The object contains two completely independent methods for loading CSS files and JS files. The parameters are the file paths to be loaded. The principle is very simple: create different nodes for different loading file types, add their respective attributes, and finally put them in the head tag. Tested, this method is compatible with various browsers and is secure, non-toxic, and environmentally friendly. It is a constant code for web developers.
The following is the call code. The exception is simple:

// Dynamically load the CSS file dynamicloading.css ("test.css"); // dynamically load the JS file dynamicLoading. js ("test. js ");

The above shows you how to dynamically load CSS and JS files using JavaScript. I hope it will be helpful for your learning.

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.