SoFunction
Updated on 2025-03-03

JavaScript implements the method of dynamically importing static resource files such as js and css

This article describes the method of javascript to dynamically import static resource files such as js and css. Share it for your reference. The specific implementation method is as follows:

/**
  * Dynamically import static resource files js/css
  */
var $import = function(){
  return function(rId, res, callback){
    if(res && 'string' == typeof res){
      if(rId){
        if($($('#' + rId), $('head')).length>0){
          return;
        }
      }
      //Load the resource file      var sType = (('.') + 1);
      // Support js/css      if(sType && ('js' == sType || 'css' == sType)){
        var isScript = (sType == 'js');
        var tag = isScript ? 'script' : 'link';
        var head = ('head')[0];
        // Create node        var linkScript = (tag);
         = isScript ? 'text/javascript' : 'text/css';
         = 'UTF-8';
        if(!isScript){
           = 'stylesheet';
        }
        isScript ?  = res :  = res;
        if(callback && 'function' == typeof callback){
          if (){
            ('load', function(){
              ();
            }, false);
          } else if () {
            ('onreadystatechange', function(){
              var target = ;
              if ( == 'complete') {
                ();
              }
            });
          }
        }
        (linkScript);
      }
    }
  };
}();

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