Home > Web Front-end > JS Tutorial > body text

How to implement JavaScript to dynamically load CSS and JS files_javascript skills

WBOY
Release: 2016-05-16 15:35:02
Original
1045 people have browsed it

Dynamic loading of CSS files is required in the project. I sorted it out and integrated the function of dynamically loading JS into an object. Let’s start with 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);
  }
}

Copy after login
The

object contains two completely independent methods, which are used to load CSS files and JS files respectively. The parameters are the file paths to be loaded. The principle is very simple: create different nodes for different loaded file types, then add their respective attributes, and finally throw them into the head tag. After testing, this method is compatible with all browsers, safe, non-toxic, and environmentally friendly, and is a common code for web developers to work with.
The following is the calling code, which is extremely simple:

//动态加载 CSS 文件
dynamicLoading.css("test.css");

//动态加载 JS 文件
dynamicLoading.js("test.js");
Copy after login

The above is to tell you how to dynamically load CSS and JS files in JavaScript. I hope it will be helpful to your learning.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!