Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Load in sections of a site via AJAX - recommended on non-essential items like a megamenu that might not be used on mobile
/**
* Template
* This allows fetching of non-essential assets via AJAX
* e.g. megamenu
* @param object, configuration parameters
*/
function Template(config) {
this.fetchFile = config.fetchFile;
this.partialsDir = config.partialsDir || '/partials/';
this.fetchURL = this.partialsDir + this.fetchFile;
// lets us know if the instance already exists on the page
this.loaded = false;
// unique identifier so we can target it and remove it when appropriate
this.instance = (this.instance || 0) + 1;
this.instanceClass = 'template-' + this.instance;
this.dataType = config.dataType || 'html';
this.insertAfter = config.insertAfter || null;
this.insertBefore = config.insertBefore || null;
this.append = config.append || null;
this.error = false;
this.errorMessage = '';
/**
* Method to be called when completed
* this might contain event handlers
*/
this.onComplete = config.onComplete || null;
// Error checking
if (
this.insertAfter === null &&
this.insertBefore === null &&
this.append === null
) {
this.error = true;
this.errorMessage = "No placement specified: insertBefore, insertAfter, append";
}
}
/**
* Loads and appends the partial to the DOM
*/
Template.prototype.load = function () {
var template = this;
if (template.loaded) {
return;
}
$.ajax({
type: 'POST',
url: template.fetchURL,
dataType: template.dataType,
success: function (data) {
if (template.error) {
console.log(template.errorMessage);
return;
}
var el = $(data).addClass(template.instanceClass);
// Decide if we should insertAfter, insertBefore or append
if (template.insertAfter !== null) {
el.insertAfter(template.insertAfter);
} else if (template.insertBefore !== null) {
el.insertBefore(template.insertBefore);
} else {
template.append.append(el);
}
template.loaded = true;
template.onComplete();
}
});
};
// Remove the template from the DOM
Template.prototype.remove = function () {
$('.' + this.instanceClass).remove();
this.loaded = false;
};
// Usage
var megamenuTemplate = new Template({
fetchFile: 'megamenu.php',
append: $('.site-header'),
onComplete: function () {
// do your event handling
}
});
if ($(window).width() > 767) {
megamenuTemplate.load();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment