1. 程式人生 > >JavaScript動態加載CSS和JS文件

JavaScript動態加載CSS和JS文件

tel path end js文件 document ava style pen bsp

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);
  }
}

//動態加載 CSS 文件
dynamicLoading.css("test.css");

//動態加載 JS 文件
dynamicLoading.js("test.js");

JavaScript動態加載CSS和JS文件