boilerplate.js
Version:
Development Tools
103 lines (82 loc) • 3.4 kB
JavaScript
// Executes page init fuction based on the URL. Example: if URL = "example.com/about-us" It will execute function named "page.aboutUs();"
window.addEventListener("load", function (event) {
window.dependencies = window.dependencies || [];
let count = dependencies.length;
function check() {
if (count === 0) {
measure('stop', 'App.js Bootstrap');
ready();
initPage();
} else {
load();
}
}
function load() {
dependencies.forEach(item => {
Defer.js(item, () => {
count--;
if (count === 0) check();
});
});
}
check();
});
function initPage(url) {
log('%cThis Is A Development Environment, Please Run "gulp js --prod"', 'background: purple; color: #fff; font-weight: bold; font-size: 1.3em; padding: 12px;');
var link = document.createElement('a');
window.init = window.init || {};
link.href = url || init.url || location.pathname;
if (link.pathname.indexOf('.') >= 0) {
var splitPath = link.pathname.split('.');
splitPath.pop();
url = splitPath.join('.');
} else {
url = link.pathname;
}
var urlSplit = (toCamelCase(url)).split('/');
window.init.urlSplit = urlSplit;
if (!urlSplit[urlSplit.length - 1]) urlSplit.pop();
var toExecute = [];
var messageOnce = false;
init.url = url;
window.$this = window.page;
urlSplit.forEach(item => {
$this = $this[item] || {};
});
$this.components = $this.components || {};
$this = $this.components;
urlSplit.forEach(x => {
toExecute.push(x);
try {
try {
var checkFunction = eval('page.' + toExecute.join('.') + '.init');
} catch (error) {
throw (error);
}
if (checkFunction) {
measure.start(toExecute.join('.') + '.init');
checkFunction();
let time = measure.stop(toExecute.join('.') + '.init', true);
log('%cpage.' + toExecute.join('.') + '.init Found! ( ' + time + ' )', 'background: green; color: #fff; padding: 10px;');
} else {
if (!messageOnce) {
log('%cCreate Init File: gulp --js ' + link.pathname, 'background: grey; color: #fff; padding: 10px;');
log('%cCreate Page Component: gulp --js ' + link.pathname + '~componentName', 'background: grey; color: #fff; padding: 10px;');
messageOnce = true;
}
log('%cFunction page.' + toExecute.join('.') + '.init Not Found!', 'background: red; color: #fff; padding: 10px;');
}
} catch (error) {
// log('%c' + error, 'background: red; color: #fff; padding: 10px;');
// console.log(error);
}
});
function toCamelCase(string) {
string = string[0] === '/' ? string.substring(1) : string;
if (string.length === 0) return 'home';
return string.replace(/(-|\_)([a-z])/g, function (g) { return g[1].toUpperCase(); });
}
}
function thisPageOnly(pathname, cb) {
if (init.url === pathname || location.pathname === pathname) cb();
}