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

How to dynamically import static resource files such as js and css using javascript_javascript skills

WBOY
Release: 2016-05-16 15:48:58
Original
1069 people have browsed it

The example in this article describes the method of dynamically importing static resource files such as js and css using javascript. Share it with everyone for your reference. The specific implementation method is as follows:

/**
 * 动态导入静态资源文件js/css
 */
var $import = function(){
  return function(rId, res, callback){
    if(res && 'string' == typeof res){
      if(rId){
        if($($('#' + rId), $('head')).length>0){
          return;
        }
      }
      //加载资源文件
      var sType = res.substring(res.lastIndexOf('.') + 1);
      // 支持js/css
      if(sType && ('js' == sType || 'css' == sType)){
        var isScript = (sType == 'js');
        var tag = isScript ? 'script' : 'link';
        var head = document.getElementsByTagName('head')[0];
        // 创建节点
        var linkScript = document.createElement(tag);
        linkScript.type = isScript ? 'text/javascript' : 'text/css';
        linkScript.charset = 'UTF-8';
        if(!isScript){
          linkScript.rel = 'stylesheet';
        }
        isScript ? linkScript.src = res : linkScript.href = res;
        if(callback && 'function' == typeof callback){
          if (linkScript.addEventListener){
            linkScript.addEventListener('load', function(){
              callback.call();
            }, false);
          } else if (linkScript.attachEvent) {
            linkScript.attachEvent('onreadystatechange', function(){
              var target = window.event.srcElement;
              if (target.readyState == 'complete') {
                callback.call();
              }
            });
          }
        }
        head.appendChild(linkScript);
      }
    }
  };
}();

Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

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