Posted By

Pjotor on 02/18/15


Tagged

jquery injection Resource deferred


Versions (?)

Bare bones require engine


 / Published in: JavaScript
 

URL: http://pjotor.com

Uses deferred to load resources async or synchronous, depending on resource type. Extendable to cover whatever type of resource needed. Wrapped in a jQuery function. (937 bytes uncompressed)

  1. /*
  2. Usage:
  3. $.Require({
  4.   scripts: "http://code.jquery.com/jquery-2.1.3.min.js",
  5.   styles: ["http://code.jquery.com/ui/1.11.3/themes/vader/jquery-ui.css"],
  6.   json: [{ url:"/echo/jsonp", arg: {text: "first text"}, target: echo }]
  7. }).done(function () {
  8.   console.log("All done and injected");
  9. });
  10. */
  11.  
  12. (function(b){b.Require=function(f){return b.when(function(){function g(c,a,d){c[a]=d;c=b.unique(b.map(c,function(b){return b}));1===c.length&&c[0]&&k.resolve()}var k=b.Deferred(),d={};b.map(f,function(b,a){d[a]=!1});b.each(f,function(c,a){a=b.isArray(a)?a:[a];switch(c){case "styles":b.each(a,function(h,e){b("<link/>",{rel:"stylesheet",type:"text/css",href:e}).load(function(){g(d,c,h===a.length-1)}).appendTo(b("head"))});break;case "handlebars":b.each(a,function(h,e){b("<script/>",{type:"text/x-handlebars-template",id:e.split("/").pop().split(".")[0]}).load(e,function(){g(d,c,h===a.length-1)}).appendTo(b("head"))});break;case "scripts":(function e(a){b.getScript(a[0],function(){1<a.length?(a=a.slice(1)).length&&e(a):g(d,c,!0)})})(a);break;case "json":(function l(a){b.getJSON(a[0].url,a[0].arg||{},function(f){b.extend(a[0].target,f);1<a.length?(a=a.slice(1)).length&&l(a):g(d,c,!0)})})(a)}});return k.promise()}())}})(jQuery);

Report this snippet  

You need to login to post a comment.