How to Implement JavaScript dynamic loading of CSS and JS file _ javascript skills

Source: Internet
Author: User
This article mainly introduces JavaScript dynamic loading of CSS and JS files. If you need it, refer to the need to use dynamic loading of CSS files in the project, by the way, the function of dynamically loading JS is integrated into an object, first the code is:

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? 1.1.9 "); // dynamically load the JS file dynamicLoading. js (" test. js? 1.1.9 ");

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.