简体   繁体   中英

Load JavaScript on demand

I am using jQuery and jQuery mobile.

I think both libraries got downloaded to my iPhone over ATT's internet, which is slow.

So I am wondering if there is some framework taking care of it and trimming the file to necessary size for functions I use in the page?

Is there also something for CSS file, which can be fat also?

Thanks

Insert this in your javascript:

var LoadedScripts = new Array();

jQuery.getScript = function(url, callback, cache){
  if ($.inArray(url, LoadedScripts) > -1) {
    callback();
  }
  else {
     LoadedScripts.push(url);       
     jQuery.ajax({
      type: "GET",
      url: url,
      success: callback,
      dataType: "script",
      cache: cache
    });
  }
};

How to use it:

function YourFunction() {
   jQuery.getScript('path/to/your/script.js',function(){  
     // your code here - the script has loaded
   },true);
}

change "true" to turn cache off and force reload of file (useful for css)

function YourFunction() {
   jQuery.getScript('path/to/your/script.js',function(){  
     // your code here - the script has loaded
   },false);
} 

YUI Compressor can be used to shrink JS and CSS files, if you're downloading someone elses library/code, they usually provide a minified version so you'll see no savings over trying to min it again. If you want to 'trim it down' to exclude parts of the library you aren't using, you may want to reconsider using a library in the first place and not just creating your own solutions for the pieces you need... but you may be surprised how useful the parts you're trying to exclude are.

<pre><code>
  function require (src, callback) {
    if (!(src != null && (typeof src == 'string' || typeof src == 'object'))) return;
    var src = typeof src == 'string' ? [src] : src;
    var total = [];
    var loaded = [];
    var failed = [];
    var fn = function (e) {
      if (e.type == 'load') loaded.push(e.target.src);
      else failed.push(e.target.src);
      if ((loaded.length + failed.length) == total.length && typeof callback == 'function') callback(!!failed.length, loaded, failed);
    };
    var load = function (src) {
      var s = document.createElement('script');
      s.type = 'application/javascript';
      s.src = src;
      s.addEventListener('error', fn, false);
      s.addEventListener('load', fn, false);
      document.getElementsByTagName('head')[0].appendChild(s);
      return s.src;
    };
    for (var i in src) {
      var s = src[i].split(/[\s,]+/);
      for (var j in s) if (total.indexOf(s[j]) < 0) total.push(load(s[j]));
    }
  }

// Usage example:
require ('script1.js, script2.js, ...', function (hasError, loaded, failed) {
  console.log(arguments);
});

</code></pre>

you can use getScript() to load additional scripts on demand are you using the minified jquery and jquery moblie files?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM