jquery如何實現動態載入CSS檔案

admin發表於2017-02-22

在應用中有時候需要動態的載入CSS檔案或者js檔案,下面是一段網路上的程式碼例項:

[JavaScript] 純文字檢視 複製程式碼
$.extend({ 
  includePath: '', 
  include: function(file) { 
    var files = typeof file == "string" ? [file]:file; 
    for (var i = 0; i < files.length; i++) { 
      var name = files<i>.replace(/^\s|\s$/g, ""); 
      var att = name.split('.'); 
      var ext = att[att.length - 1].toLowerCase(); 
      var isCSS = ext == "css"; 
      var tag = isCSS ? "link" : "script"; 
      var attr = isCSS ? " type='text/css' rel='stylesheet' " : " type='text/javascript' "; 
      var link = (isCSS ? "href" : "src") + "='" + $.includePath + name + "'"; 
      if ($(tag + "[" + link + "]").length == 0) document.write("<" + tag + attr + link + "></" + tag + ">"); 
    } 
  } 
})
//使用方法 
$.includePath = 'http://hi.baidu.com/javascript/'; 
$.include(['json2.js', 'jquery.tree.js', 'jquery.tree.css']); </i>

相關文章