MDL-57009 javascript: Dont rely on async ajax
Recursively pre-scan mustache templates to extract the list of blocks and partials. Then we can pre-fetch them all and don't have to rely on jquery async ajax (which is deprecated). This is part of a refactoring of the promises code in the templates module to prevent duplicate requests.
This commit is contained in:
Vendored
+1
-1
@@ -1 +1 @@
|
||||
define(["core/mustache","jquery","core/ajax","core/str","core/notification","core/url","core/config","core/localstorage","core/event","core/yui","core/log"],function(a,b,c,d,e,f,g,h,i,j,k){var l=0,m={},n=[],o=function(){this.requiredStrings=[],this.requiredJS=[],this.currentThemeName=""};o.prototype.requiredStrings=null,o.prototype.requiredJS=null,o.prototype.currentThemeName="",o.prototype.getTemplate=function(a,d){var e=a.split("/"),f=e.shift(),g=e.shift(),i=this.currentThemeName+"/"+a;if(i in m)return m[i];var j=h.get("core_template/"+i);if(j)return m[i]=b.Deferred().resolve(j).promise(),m[i];var k=c.call([{methodname:"core_output_load_template",args:{component:f,template:g,themename:this.currentThemeName}}],d,!1);return m[i]=k[0].then(function(a){return h.set("core_template/"+i,a),a}),m[i]},o.prototype.partialHelper=function(a){var b="";return this.getTemplate(a,!1).done(function(a){b=a}).fail(e.exception),b},o.prototype.pixHelper=function(b,c,d){var e,g=c.split(","),h="",i="",j="";g.length>0&&(h=g.shift().trim()),g.length>0&&(i=g.shift().trim()),g.length>0&&(j=g.join(",").trim());var k=f.imageUrl(h,i),l={attributes:[{name:"src",value:k},{name:"alt",value:d(j)},{name:"title",value:d(j)},{name:"class",value:"smallicon"}]},m=n[this.currentThemeName];return e=a.render(m,l,this.partialHelper.bind(this)),e.trim()},o.prototype.jsHelper=function(a,b,c){return this.requiredJS.push(c(b,a)),""},o.prototype.stringHelper=function(a,b,c){var d=b.split(","),e="",f="",g="";d.length>0&&(e=d.shift().trim()),d.length>0&&(f=d.shift().trim()),d.length>0&&(g=d.join(",").trim()),""!==g&&(g=c(g,a)),0===g.indexOf("{")&&0!==g.indexOf("{{")&&(g=JSON.parse(g));var h=this.requiredStrings.length;return this.requiredStrings.push({key:e,component:f,param:g}),"[[_s"+h+"]]"},o.prototype.quoteHelper=function(a,b,c){var d=c(b.trim(),a);return d=d.replace('"','\\"').replace(/([\{\}]{2,3})/g,"{{=<% %>=}}$1<%={{ }}=%>"),'"'+d+'"'},o.prototype.addHelpers=function(a,b){this.currentThemeName=b,this.requiredStrings=[],this.requiredJS=[],a.uniqid=l++,a.str=function(){return this.stringHelper.bind(this,a)}.bind(this),a.pix=function(){return this.pixHelper.bind(this,a)}.bind(this),a.js=function(){return this.jsHelper.bind(this,a)}.bind(this),a.quote=function(){return this.quoteHelper.bind(this,a)}.bind(this),a.globals={config:g},a.currentTheme=b},o.prototype.getJS=function(a){var b="";return this.requiredJS.length>0&&(b=this.requiredJS.join(";\n")),this.treatStringsInContent(b,a)},o.prototype.treatStringsInContent=function(a,b){var c,d,e,f,g,h,i=/\[\[_s\d+\]\]/;do{for(c="",d=a.search(i);d>-1;){c+=a.substring(0,d),a=a.substr(d),e="",f=4,g=a.substr(f,1);do e+=g,f++,g=a.substr(f,1);while("]"!=g);h=b[parseInt(e,10)],"undefined"==typeof h&&(k.debug("Could not find string for pattern [[_s"+e+"]]."),h=""),c+=h,a=a.substr(6+e.length),d=a.search(i)}a=c+a,d=a.search(i)}while(d>-1);return a},o.prototype.doRender=function(c,e,f){return this.currentThemeName=f,this.getTemplate("core/pix_icon",!0).then(function(a){n[this.currentThemeName]=a}.bind(this)).then(function(){this.addHelpers(e,f);var g=a.render(c,e,this.partialHelper.bind(this));return this.requiredStrings.length>0?d.get_strings(this.requiredStrings).then(function(a){return g=this.treatStringsInContent(g,a),b.Deferred().resolve(g,this.getJS(a)).promise()}.bind(this)):b.Deferred().resolve(g.trim(),this.getJS([])).promise()}.bind(this))};var p=function(a){if(""!==a.trim()){var c=b("<script>").attr("type","text/javascript").html(a);b("head").append(c)}},q=function(a,c,d,e){var f=b(a);if(f.length){var g=b(c),h=null;e?(h=new j.NodeList(f.children().get()),h.destroy(!0),f.empty(),f.append(g)):(h=new j.NodeList(f.get()),h.destroy(!0),f.replaceWith(g)),p(d),i.notifyFilterContentUpdated(g)}};o.prototype.render=function(a,b,c){return"undefined"==typeof c&&(c=g.theme),this.currentThemeName=c,this.getTemplate(a,!0).then(function(a){return this.doRender(a,b,c)}.bind(this))};var r=function(a,c,d){var e=b(a);e.length&&(e.prepend(c),p(d),i.notifyFilterContentUpdated(e))},s=function(a,c,d){var e=b(a);e.length&&(e.append(c),p(d),i.notifyFilterContentUpdated(e))};return{render:function(a,b,c){var d=new o;return d.render(a,b,c)},runTemplateJS:p,replaceNodeContents:function(a,b,c){q(a,b,c,!0)},replaceNode:function(a,b,c){q(a,b,c,!1)},prependNodeContents:function(a,b,c){r(a,b,c)},appendNodeContents:function(a,b,c){s(a,b,c)}}});
|
||||
define(["core/mustache","jquery","core/ajax","core/str","core/notification","core/url","core/log","core/config","core/localstorage","core/event","core/yui","core/log"],function(a,b,c,d,e,f,g,h,i,j,k,l){var m=0,n={},o={},p=function(){this.requiredStrings=[],this.requiredJS=[],this.currentThemeName=""};p.prototype.requiredStrings=null,p.prototype.requiredJS=null,p.prototype.currentThemeName="",p.prototype.getTemplate=function(a){var d=a.split("/"),e=d.shift(),f=d.shift(),g=this.currentThemeName+"/"+a;if(g in o)return o[g];var h=i.get("core_template/"+g);if(h)return n[g]=h,o[g]=b.Deferred().resolve(h).promise(),o[g];var j=c.call([{methodname:"core_output_load_template",args:{component:e,template:f,themename:this.currentThemeName}}],!0,!1);return o[g]=j[0].then(function(a){return n[g]=a,i.set("core_template/"+g,a),a}),o[g]},p.prototype.partialHelper=function(a){var b=this.currentThemeName+"/"+a;return b in n||e.exception(new Error("Failed to pre-fetch the template: "+a)),n[b]},p.prototype.pixHelper=function(b,c,d){var e,g=c.split(","),h="",i="",j="";g.length>0&&(h=g.shift().trim()),g.length>0&&(i=g.shift().trim()),g.length>0&&(j=g.join(",").trim());var k=f.imageUrl(h,i),l={attributes:[{name:"src",value:k},{name:"alt",value:d(j)},{name:"title",value:d(j)},{name:"class",value:"smallicon"}]},m=this.currentThemeName+"/core/pix_icon",o=n[m];return e=a.render(o,l,this.partialHelper.bind(this)),e.trim()},p.prototype.jsHelper=function(a,b,c){return this.requiredJS.push(c(b,a)),""},p.prototype.stringHelper=function(a,b,c){var d=b.split(","),e="",f="",g="";d.length>0&&(e=d.shift().trim()),d.length>0&&(f=d.shift().trim()),d.length>0&&(g=d.join(",").trim()),""!==g&&(g=c(g,a)),0===g.indexOf("{")&&0!==g.indexOf("{{")&&(g=JSON.parse(g));var h=this.requiredStrings.length;return this.requiredStrings.push({key:e,component:f,param:g}),"[[_s"+h+"]]"},p.prototype.quoteHelper=function(a,b,c){var d=c(b.trim(),a);return d=d.replace('"','\\"').replace(/([\{\}]{2,3})/g,"{{=<% %>=}}$1<%={{ }}=%>"),'"'+d+'"'},p.prototype.addHelpers=function(a,b){this.currentThemeName=b,this.requiredStrings=[],this.requiredJS=[],a.uniqid=m++,a.str=function(){return this.stringHelper.bind(this,a)}.bind(this),a.pix=function(){return this.pixHelper.bind(this,a)}.bind(this),a.js=function(){return this.jsHelper.bind(this,a)}.bind(this),a.quote=function(){return this.quoteHelper.bind(this,a)}.bind(this),a.globals={config:h},a.currentTheme=b},p.prototype.getJS=function(a){var b="";return this.requiredJS.length>0&&(b=this.requiredJS.join(";\n")),this.treatStringsInContent(b,a)},p.prototype.treatStringsInContent=function(a,b){var c,d,e,f,g,h,i=/\[\[_s\d+\]\]/;do{for(c="",d=a.search(i);d>-1;){c+=a.substring(0,d),a=a.substr(d),e="",f=4,g=a.substr(f,1);do e+=g,f++,g=a.substr(f,1);while("]"!=g);h=b[parseInt(e,10)],"undefined"==typeof h&&(l.debug("Could not find string for pattern [[_s"+e+"]]."),h=""),c+=h,a=a.substr(6+e.length),d=a.search(i)}a=c+a,d=a.search(i)}while(d>-1);return a},p.prototype.doRender=function(c,e,f){return this.currentThemeName=f,this.getTemplate("core/pix_icon").then(function(){this.addHelpers(e,f);var g=a.render(c,e,this.partialHelper.bind(this));return this.requiredStrings.length>0?d.get_strings(this.requiredStrings).then(function(a){return g=this.treatStringsInContent(g,a),b.Deferred().resolve(g,this.getJS(a)).promise()}.bind(this)):b.Deferred().resolve(g.trim(),this.getJS([])).promise()}.bind(this))};var q=function(a){if(""!==a.trim()){var c=b("<script>").attr("type","text/javascript").html(a);b("head").append(c)}},r=function(a,c,d,e){var f=b(a);if(f.length){var g=b(c),h=null;e?(h=new k.NodeList(f.children().get()),h.destroy(!0),f.empty(),f.append(g)):(h=new k.NodeList(f.get()),h.destroy(!0),f.replaceWith(g)),q(d),j.notifyFilterContentUpdated(g)}};p.prototype.scanForPartials=function(b){var c=a.parse(b),d=[],e=function(a,b){var c,d;for(c=0;c<a.length;c++)d=a[c],">"!=d[0]&&"<"!=d[0]||b.push(d[1]),d.length>4&&e(d[4],b)};return e(c,d),d},p.prototype.cachePartials=function(a){return this.getTemplate(a).then(function(a){var c,d=this.scanForPartials(a),e=[];for(c=0;c<d.length;c++){var f=this.currentThemeName+"/"+d[c];f in o||e.push(this.cachePartials(d[c]))}return b.when(e).then(function(){return a}.bind(this))}.bind(this))},p.prototype.render=function(a,b,c){return"undefined"==typeof c&&(c=h.theme),this.currentThemeName=c,this.cachePartials(a).then(function(a){return this.doRender(a,b,c)}.bind(this))};var s=function(a,c,d){var e=b(a);e.length&&(e.prepend(c),q(d),j.notifyFilterContentUpdated(e))},t=function(a,c,d){var e=b(a);e.length&&(e.append(c),q(d),j.notifyFilterContentUpdated(e))};return{render:function(a,b,c){var d=new p;return d.render(a,b,c)},runTemplateJS:q,replaceNodeContents:function(a,b,c){r(a,b,c,!0)},replaceNode:function(a,b,c){r(a,b,c,!1)},prependNodeContents:function(a,b,c){s(a,b,c)},appendNodeContents:function(a,b,c){t(a,b,c)}}});
|
||||
+85
-27
@@ -29,23 +29,24 @@ define(['core/mustache',
|
||||
'core/str',
|
||||
'core/notification',
|
||||
'core/url',
|
||||
'core/log',
|
||||
'core/config',
|
||||
'core/localstorage',
|
||||
'core/event',
|
||||
'core/yui',
|
||||
'core/log'
|
||||
],
|
||||
function(mustache, $, ajax, str, notification, coreurl, config, storage, event, Y, Log) {
|
||||
function(mustache, $, ajax, str, notification, coreurl, log, config, storage, event, Y, Log) {
|
||||
|
||||
// Module variables.
|
||||
/** @var {Number} uniqInstances Count of times this constructor has been called. */
|
||||
var uniqInstances = 0;
|
||||
|
||||
/** @var {string[]} templateCache - Cache of already loaded templates */
|
||||
/** @var {String[]} templateCache - Cache of already loaded template strings */
|
||||
var templateCache = {};
|
||||
|
||||
/** @var {string[]} pixTemplateCache - The pix icon template must be cached as a string (once per theme) */
|
||||
var pixTemplateCache = [];
|
||||
/** @var {Promise[]} templatePromises - Cache of already loaded template promises */
|
||||
var templatePromises = {};
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
@@ -76,10 +77,9 @@ define(['core/mustache',
|
||||
* @param {string} templateName - should consist of the component and the name of the template like this:
|
||||
* core/menu (lib/templates/menu.mustache) or
|
||||
* tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
|
||||
* @param {Boolean} async If false - this function will not return until the promises are resolved.
|
||||
* @return {Promise} JQuery promise object resolved when the template has been fetched.
|
||||
*/
|
||||
Renderer.prototype.getTemplate = function(templateName, async) {
|
||||
Renderer.prototype.getTemplate = function(templateName) {
|
||||
var parts = templateName.split('/');
|
||||
var component = parts.shift();
|
||||
var name = parts.shift();
|
||||
@@ -87,16 +87,17 @@ define(['core/mustache',
|
||||
var searchKey = this.currentThemeName + '/' + templateName;
|
||||
|
||||
// First try request variables.
|
||||
if (searchKey in templateCache) {
|
||||
return templateCache[searchKey];
|
||||
if (searchKey in templatePromises) {
|
||||
return templatePromises[searchKey];
|
||||
}
|
||||
|
||||
// Now try local storage.
|
||||
var cached = storage.get('core_template/' + searchKey);
|
||||
|
||||
if (cached) {
|
||||
templateCache[searchKey] = $.Deferred().resolve(cached).promise();
|
||||
return templateCache[searchKey];
|
||||
templateCache[searchKey] = cached;
|
||||
templatePromises[searchKey] = $.Deferred().resolve(cached).promise();
|
||||
return templatePromises[searchKey];
|
||||
}
|
||||
|
||||
// Oh well - load via ajax.
|
||||
@@ -107,15 +108,16 @@ define(['core/mustache',
|
||||
template: name,
|
||||
themename: this.currentThemeName
|
||||
}
|
||||
}], async, false);
|
||||
}], true, false);
|
||||
|
||||
templateCache[searchKey] = promises[0].then(
|
||||
templatePromises[searchKey] = promises[0].then(
|
||||
function(templateSource) {
|
||||
templateCache[searchKey] = templateSource;
|
||||
storage.set('core_template/' + searchKey, templateSource);
|
||||
return templateSource;
|
||||
}
|
||||
);
|
||||
return templateCache[searchKey];
|
||||
return templatePromises[searchKey];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -127,16 +129,14 @@ define(['core/mustache',
|
||||
* @return {string}
|
||||
*/
|
||||
Renderer.prototype.partialHelper = function(name) {
|
||||
var template = '';
|
||||
|
||||
// Don't use "then" here it will always be async even if the promise is resolved immediately.
|
||||
this.getTemplate(name, false).done(
|
||||
function(source) {
|
||||
template = source;
|
||||
}
|
||||
).fail(notification.exception);
|
||||
var searchKey = this.currentThemeName + '/' + name;
|
||||
|
||||
return template;
|
||||
if (!(searchKey in templateCache)) {
|
||||
notification.exception(new Error('Failed to pre-fetch the template: ' + name));
|
||||
}
|
||||
|
||||
return templateCache[searchKey];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -176,7 +176,8 @@ define(['core/mustache',
|
||||
]
|
||||
};
|
||||
// We forced loading of this early, so it will be in the cache.
|
||||
var template = pixTemplateCache[this.currentThemeName];
|
||||
var searchKey = this.currentThemeName + '/core/pix_icon';
|
||||
var template = templateCache[searchKey];
|
||||
result = mustache.render(template, templatecontext, this.partialHelper.bind(this));
|
||||
return result.trim();
|
||||
};
|
||||
@@ -390,10 +391,7 @@ define(['core/mustache',
|
||||
Renderer.prototype.doRender = function(templateSource, context, themeName) {
|
||||
this.currentThemeName = themeName;
|
||||
|
||||
return this.getTemplate('core/pix_icon', true).then(function(str) {
|
||||
// Make sure we fetch this first.
|
||||
pixTemplateCache[this.currentThemeName] = str;
|
||||
}.bind(this)).then(function() {
|
||||
return this.getTemplate('core/pix_icon').then(function() {
|
||||
this.addHelpers(context, themeName);
|
||||
var result = mustache.render(templateSource, context, this.partialHelper.bind(this));
|
||||
|
||||
@@ -470,6 +468,66 @@ define(['core/mustache',
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Scan a template source for partial tags and return a list of the found partials.
|
||||
*
|
||||
* @method scanForPartials
|
||||
* @private
|
||||
* @param {string} templateSource - source template to scan.
|
||||
* @return {Array} List of partials.
|
||||
*/
|
||||
Renderer.prototype.scanForPartials = function(templateSource) {
|
||||
var tokens = mustache.parse(templateSource),
|
||||
partials = [];
|
||||
|
||||
var findPartial = function(tokens, partials) {
|
||||
var i, token;
|
||||
for (i = 0; i < tokens.length; i++) {
|
||||
token = tokens[i];
|
||||
if (token[0] == '>' || token[0] == '<') {
|
||||
partials.push(token[1]);
|
||||
}
|
||||
if (token.length > 4) {
|
||||
findPartial(token[4], partials);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
findPartial(tokens, partials);
|
||||
|
||||
return partials;
|
||||
};
|
||||
|
||||
/**
|
||||
* Load a template and scan it for partials. Recursively fetch the partials.
|
||||
*
|
||||
* @method cachePartials
|
||||
* @private
|
||||
* @param {string} templateName - should consist of the component and the name of the template like this:
|
||||
* core/menu (lib/templates/menu.mustache) or
|
||||
* tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
|
||||
* @return {Promise} JQuery promise object resolved when all partials are in the cache.
|
||||
*/
|
||||
Renderer.prototype.cachePartials = function(templateName) {
|
||||
return this.getTemplate(templateName).then( function(templateSource) {
|
||||
var i;
|
||||
var partials = this.scanForPartials(templateSource);
|
||||
var fetchThemAll = [];
|
||||
|
||||
for (i = 0; i < partials.length; i++) {
|
||||
var searchKey = this.currentThemeName + '/' + partials[i];
|
||||
if (searchKey in templatePromises) {
|
||||
continue;
|
||||
}
|
||||
fetchThemAll.push(this.cachePartials(partials[i]));
|
||||
}
|
||||
|
||||
return $.when(fetchThemAll).then(function() {
|
||||
return templateSource;
|
||||
}.bind(this));
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
/**
|
||||
* Load a template and call doRender on it.
|
||||
*
|
||||
@@ -490,7 +548,7 @@ define(['core/mustache',
|
||||
|
||||
this.currentThemeName = themeName;
|
||||
|
||||
return this.getTemplate(templateName, true).then( function(templateSource) {
|
||||
return this.cachePartials(templateName).then( function(templateSource) {
|
||||
return this.doRender(templateSource, context, themeName);
|
||||
}.bind(this) );
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user