load scripts asynchronously

前端 未结 19 1208
粉色の甜心
粉色の甜心 2020-11-22 12:01

I am using several plugins, custom widgets and some other libraries from JQuery. as a result I have several .js and .css files. I need to create a loader for my site because

19条回答
  •  孤城傲影
    2020-11-22 12:39

    I would complete zzzzBov's answer with a check for the presence of callback and allow passing of arguments:

        function loadScript(src, callback, args) {
          var s, r, t;
          r = false;
          s = document.createElement('script');
          s.type = 'text/javascript';
          s.src = src;
          if (typeof(callback) === 'function') {
            s.onload = s.onreadystatechange = function() {
              if (!r && (!this.readyState || this.readyState === 'complete')) {
                r = true;
                callback.apply(args);
              }
            };
          };
          t = document.getElementsByTagName('script')[0];
          t.parent.insertBefore(s, t);
        }
    

提交回复
热议问题