Team:HSAAHNU Anhui/inject.js

From 2014hs.igem.org

(Difference between revisions)
(IE doesn't support main element)
(using foundation 5)
 
(11 intermediate revisions not shown)
Line 1: Line 1:
/*
/*
-
  * Basically this script will do the following thing:
+
  * By Minsheng Liu from HSAAHNU_Anhui.
-
* Remove old styles.
+
  * Released under MIT License.
-
* Remove old script tags.
+
-
* Apply common stylesheets. (Bootstrap, NProgress)
+
-
* Apply common scripts. (jQuery, Bootstrap, NProgress)
+
-
* Update jQuery.
+
-
* move inner HTML of main tag to body tag for clarity.
+
-
* Clean up script tags in head tag for debugging purpose.
+
-
* Set up PJAX for better performance.
+
-
  * Complete page specific jobs.
+
  */
  */
-
 
-
var commonStylesheets = [
 
-
  'http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css',
 
-
  'http://ricostacruz.com/nprogress/nprogress.css',
 
-
  '/Team:HSAAHNU_Anhui/normalize.css?action=raw&ctype=text/css'
 
-
];
 
-
 
-
var commonScripts = [
 
-
  'http://code.jquery.com/jquery-1.11.1.min.js',
 
-
  'http://ricostacruz.com/nprogress/nprogress.js'
 
-
];
 
function cleanup () {
function cleanup () {
-
  function removeNodesFromHead (tag, constriant) {
 
-
    constriant = constriant ? constriant
 
-
                            : function () { return true; };
 
-
    var nodes = document.head.getElementsByTagName(tag);
 
-
    var failedCounter = 0;
 
-
    var iterator = 0;
 
-
    while (nodes.length !== failedCounter) {
 
-
      var node = nodes[iterator];
 
-
      if (constriant(node))
 
-
        document.head.removeChild(node);
 
-
      else {
 
-
        failedCounter ++;
 
-
        iterator ++;
 
-
      }
 
-
    }
 
-
  };
 
-
 
   removeNodesFromHead('style');
   removeNodesFromHead('style');
   removeNodesFromHead('script');
   removeNodesFromHead('script');
Line 48: Line 12:
   });
   });
-
   //since Internet Explorer doesn't support main tag yet.
+
   document.body.innerHTML = '<h1>Loading...</h1>';
-
  //boycott Internet Explorer with me, please.
+
-
  var main = document.body.getElementById('main');
+
-
  document.body.innerHTML = main.innerHTML;
+
}
}
-
function applyCommonResources () {
+
function loadResources () {
-
   function applyResources (factory, urls) {
+
   generateResourceNodes(basicStyles, 'link', function (node, url) {
-
    urls.forEach(function (url) {
+
-
      var node = factory(url);
+
-
      document.head.appendChild(node);
+
-
    });
+
-
  };
+
-
 
+
-
  applyResources(function (url) {
+
-
    var node = document.createElement('link');
+
     node.href = url;
     node.href = url;
     node.rel = 'stylesheet';
     node.rel = 'stylesheet';
-
    return node;
+
   });
-
   }, commonStylesheets);
+
   generateResourceNodes(basicScripts, 'script', function (node, url) {
-
   applyResources(function (url) {
+
-
    var node = document.createElement('script');
+
     node.src = url;
     node.src = url;
-
    return node;
+
   });
-
   }, commonScripts);
+
-
   var meta = document.createElement('meta');
+
   enableMobileDeviceSupport();
-
   meta.name = 'viewport';
+
   callHTML5Shiv();
-
  meta.content = 'width=device-width, initial-scale=1';
+
-
  document.head.appendChild(meta);
+
}
}
-
var crucialComponentLoadingTime = 0;
+
var scriptsLoadingTime = 0;
-
function waitForComponents () {
+
function waitForScripts () {
-
  //16 seconds is long enough.
+
   var isTimeout = scriptsLoadingTime > 160;
-
   var isLoadFailed = crucialComponentLoadingTime >= 32;
+
   if (isTimeout) {
-
   if (isLoadFailed) {
+
     alert('Loading script timeout. Refresh or check your Internet connection.');
-
     alert('One component of this page failed to load. Please refresh!');
+
     return;
     return;
   }
   }
Line 92: Line 39:
                         $.fn.jquery === '1.11.1';
                         $.fn.jquery === '1.11.1';
   var isNProgressLoaded = window.hasOwnProperty('NProgress');
   var isNProgressLoaded = window.hasOwnProperty('NProgress');
-
   if (isJQueryUpdated && isNProgressLoaded) {
+
 
-
     alert('done');
+
   if (isJQueryUpdated && isNProgressLoaded)
-
    completePageSpecificJobs();
+
     loadPage(parseURL(document.URL));
-
  }
+
   else {
   else {
-
     crucialComponentLoadingTime ++;
+
     scriptsLoadingTime ++;
-
     setTimeout(waitForComponents, 500);
+
     setTimeout(waitForScripts, 100);
   }
   }
}
}
-
document.addEventListener('DOMContentLoaded', function () {
+
function loadPage (path) {
-
   cleanup();
+
   NProgress.start();
-
   applyCommonResources();
+
   path.fetch(function (err, data) {
-
  waitForComponents();
+
    if (err) {
-
});
+
      alert('Error happens when loading page!');
 +
      return;
 +
    }
-
function fetchData (path, callback) {
+
    data = selectCore(PJAXSplitter.start, PJAXSplitter.end, data);
-
  var isPathString = typeof path === 'string';
+
     document.body.innerHTML = data;
-
  if (!isPathString) {
+
     doPageSpecificJobs();
-
     var team = '/Team:HSAAHNU_Anhui';
+
-
    var query = '?action=raw&ctype=text/css';
+
-
    path = team + path.href + query;
+
-
  }
+
-
  $.ajax(path).done(function (data) {
+
-
     callback(null, data);
+
-
  });
+
-
}
+
-
function loadNewPage (path) {
 
-
  NProgress.start();
 
-
  fetchData(path, function (err, data) {
 
-
    data = data.split('<main>')[1];
 
-
    data = data.split('</main>')[0];
 
-
    document.body.innerHTML = data;
 
-
    completePageSpecificJobs();
 
     NProgress.done();
     NProgress.done();
   });
   });
}
}
-
function startsWith (lhs, rhs) {
+
function setupPJAXListener () {
-
   return lhs.substr(0, rhs.length) === rhs;
+
   if (history === null) {
 +
    alert('sorry but your browser does not support history api.');
 +
    return;
 +
  }
 +
 
 +
  $('a').click(goForwardListener);
}
}
-
function analyzeAnchor (href) {
+
function applyMetadata (metadata) {
-
   var basePath = 'https://2014hs.igem.org/Team:HSAAHNU_Anhui';
+
   metadata = JSON.parse(metadata);
-
  var isOutsideLink = !startsWith(href, basePath);
+
-
  if (isOutsideLink)
+
-
    return false;
+
-
   var current = document.URL.substr(basePath.length).split('#');
+
   metadata.title ? document.title = metadata.title : null;
-
  var next = href.substr(basePath.length).split('#');
+
}
-
   var isSamePage = current[0] === next[0];
+
function doPageSpecificJobs () {
-
   if (isSamePage)
+
   setupPJAXListener();
-
    return false;
+
   applyMetadata(document.getElementById('metadata').innerText);
 +
}
-
   return {
+
//helper functions
-
     href: next[0],
+
function removeNodesFromHead (tag, constriant) {
-
     anchor: next[1],
+
   constriant = constriant ? constriant
-
   };
+
                          : function () { return true; };
 +
  var nodes = document.head.getElementsByTagName(tag);
 +
  var failedCounter = 0;
 +
  var iterator = 0;
 +
  while (nodes.length !== failedCounter) {
 +
     var node = nodes[iterator];
 +
     if (constriant(node))
 +
      document.head.removeChild(node);
 +
    else {
 +
      failedCounter ++;
 +
      iterator ++;
 +
    }
 +
   }
}
}
 +
function generateResourceNodes (urls, tagname, process) {
 +
  urls.forEach(function (url) {
 +
    var node = document.createElement(tagname);
 +
    process(node, url);
 +
    document.head.appendChild(node);
 +
  });
 +
};
-
var PJAXEnabledOnce = false;
+
function enableMobileDeviceSupport () {
-
function setupPJAXListener () {
+
   var meta = document.createElement('meta');
-
   if (history === null) {
+
  meta.name = 'viewport';
-
    alert('sorry but your browser does not support history api.');
+
   meta.content = 'width=device-width, initial-scale=1';
-
    return;
+
  document.head.appendChild(meta);
-
   }
+
}
-
  alert('it works.');
+
var html5shiv = '/*@preserve HTML5 Shiv 3.7.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed*/\n!function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=t.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=t.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),t.elements=c+" "+a,j(b)}function f(a){var b=s[a[q]];return b||(b={},r++,a[q]=r,s[r]=b),b}function g(a,c,d){if(c||(c=b),l)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():p.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||o.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),l)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return t.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\\w\\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),\'c("\'+a+\'")\'})+");return n}")(t,b.frag)}function j(a){a||(a=b);var d=f(a);return!t.shivCSS||k||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),l||i(a,d),a}var k,l,m="3.7.2",n=a.html5||{},o=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,p=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,q="_html5shiv",r=0,s={};!function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",k="hidden"in a,l=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){k=!0,l=!0}}();var t={elements:n.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:m,shivCSS:n.shivCSS!==!1,supportsUnknownElements:l,shivMethods:n.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=t,j(b)}(this,document);\n';
 +
function callHTML5Shiv () {
 +
  eval(html5shiv);
 +
}
-
  function anchorClickListener (event) {
+
var pjaxCalledOnce = false;
-
    var node = event.target;
+
function goForwardListener (event) {
-
    var path = analyzeAnchor(node.href);
+
  var node = event.target;
-
    if (path === false)
+
  var url = parseURL(node.href);
-
      return true;
+
  if (url === null)
 +
    return true;
-
    history.pushState(null, null, node.href);
+
  history.pushState(null, null, node.href);
-
    loadNewPage(path);
+
  loadPage(url);
-
    if (!PJAXEnabledOnce) {
+
  if (!pjaxCalledOnce) {
-
      PJAXEnabledOnce = true;
+
    pjaxCalledOnce = true;
-
      window.addEventListener('popstate', goBackListener);
+
    window.addEventListener('popstate', goBackListener);
-
    }
+
-
    return false;
+
   }
   }
 +
  return false;
 +
}
-
  function goBackListener (event) {
+
function goBackListener (event) {
-
    console.log('Go back to last path:', document.URL);
+
  var url = parseURL(document.URL);
-
     loadNewPage(document.URL);
+
  if (url === null)
-
  }
+
     return;
 +
  loadPage(parseURL(document.URL));
 +
}
-
   $('a').click(anchorClickListener);
+
function checkURLForPJAX (url) {
 +
   var isOutsideLink = !startsWith(href, basePath);
 +
  if (isOutsideLink)
 +
    return;
 +
 
 +
  var current = parseURL(document.URL);
 +
  var next = parseURL(url);
 +
 
 +
  var isSamePage = current.path === next.path;
 +
  if (isSamePage)
 +
    return;
 +
  else
 +
    return next;
}
}
-
function completePageSpecificJobs () {
+
function parseURL (url) {
-
   setupPJAXListener();
+
   var info = url.substr(basePath.length).split('#');
 +
  return {
 +
    path: info[0],
 +
    anchor: info[1],
 +
    fetch: function (callback) {
 +
      var url = basePath + this.path + mediaWikiRawQuery;
 +
      $.ajax(url).done(function (data) { callback(null, data); });
 +
    }
 +
  };
 +
}
-
   var metadata = $('#metadata')[0].innerText;
+
//utility functions
-
   metadata = JSON.parse(metadata);
+
function startsWith (lhs, rhs) {
 +
   var isStartWith = lhs.substr(0, rhs.length) === rhs;
 +
   return isStartWith;
 +
}
-
   metadata.title ? $('title')[0].innerText = metadata.title : null;
+
function selectCore (from, to, str) {
 +
   return str.split(from)[1].split(to)[0];
}
}
 +
 +
//magic "numbers"
 +
var basicStyles = [
 +
  'http://cdnjs.cloudflare.com/ajax/libs/foundation/5.2.3/css/foundation.min.css',
 +
  'http://ricostacruz.com/nprogress/nprogress.css',
 +
  '/Team:HSAAHNU_Anhui/normalize.css?action=raw&ctype=text/css'
 +
];
 +
 +
var basicScripts = [
 +
  'http://code.jquery.com/jquery-1.11.1.min.js',
 +
  'http://ricostacruz.com/nprogress/nprogress.js'
 +
];
 +
 +
var PJAXSplitter = {
 +
  start: '<!-- PJAX Content Start -->',
 +
  end: '<!-- PJAX Content Start -->'
 +
};
 +
 +
var basePath = 'https://2014hs.igem.org/Team:HSAAHNU_Anhui';
 +
var mediaWikiRawQuery = '?action=raw';
 +
 +
document.addEventListener('DOMContentLoaded', function () {
 +
  cleanup();
 +
  loadResources();
 +
  waitForScripts();
 +
});

Latest revision as of 08:25, 15 June 2014

/*

* By Minsheng Liu from HSAAHNU_Anhui.
* Released under MIT License.
*/

function cleanup () {

 removeNodesFromHead('style');
 removeNodesFromHead('script');
 removeNodesFromHead('link', function (node) {
   var isStylesheet = node.rel === 'stylesheet';
   return isStylesheet;
 });
document.body.innerHTML = '

Loading...

';

}

function loadResources () {

 generateResourceNodes(basicStyles, 'link', function (node, url) {
   node.href = url;
   node.rel = 'stylesheet';
 });
 generateResourceNodes(basicScripts, 'script', function (node, url) {
   node.src = url;
 });
 enableMobileDeviceSupport();
 callHTML5Shiv();

}

var scriptsLoadingTime = 0; function waitForScripts () {

 var isTimeout = scriptsLoadingTime > 160;
 if (isTimeout) {
   alert('Loading script timeout. Refresh or check your Internet connection.');
   return;
 }
 var isJQueryUpdated = window.hasOwnProperty('jQuery') &&
                       $.fn.jquery === '1.11.1';
 var isNProgressLoaded = window.hasOwnProperty('NProgress');
 if (isJQueryUpdated && isNProgressLoaded)
   loadPage(parseURL(document.URL));
 else {
   scriptsLoadingTime ++;
   setTimeout(waitForScripts, 100);
 }

}

function loadPage (path) {

 NProgress.start();
 path.fetch(function (err, data) {
   if (err) {
     alert('Error happens when loading page!');
     return;
   }
   data = selectCore(PJAXSplitter.start, PJAXSplitter.end, data);
   document.body.innerHTML = data;
   doPageSpecificJobs();
   NProgress.done();
 });

}

function setupPJAXListener () {

 if (history === null) {
   alert('sorry but your browser does not support history api.');
   return;
 }
 $('a').click(goForwardListener);

}

function applyMetadata (metadata) {

 metadata = JSON.parse(metadata);
 metadata.title ? document.title = metadata.title : null;

}

function doPageSpecificJobs () {

 setupPJAXListener();
 applyMetadata(document.getElementById('metadata').innerText);

}

//helper functions function removeNodesFromHead (tag, constriant) {

 constriant = constriant ? constriant
                         : function () { return true; };
 var nodes = document.head.getElementsByTagName(tag);
 var failedCounter = 0;
 var iterator = 0;
 while (nodes.length !== failedCounter) {
   var node = nodes[iterator];
   if (constriant(node))
     document.head.removeChild(node);
   else {
     failedCounter ++;
     iterator ++;
   }
 }

}

function generateResourceNodes (urls, tagname, process) {

 urls.forEach(function (url) {
   var node = document.createElement(tagname);
   process(node, url);
   document.head.appendChild(node);
 });

};

function enableMobileDeviceSupport () {

 var meta = document.createElement('meta');
 meta.name = 'viewport';
 meta.content = 'width=device-width, initial-scale=1';
 document.head.appendChild(meta);

}

var html5shiv = '/*@preserve HTML5 Shiv 3.7.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed*/\n!function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=t.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=t.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),t.elements=c+" "+a,j(b)}function f(a){var b=s[a[q]];return b||(b={},r++,a[q]=r,s[r]=b),b}function g(a,c,d){if(c||(c=b),l)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():p.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||o.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),l)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return t.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\\w\\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),\'c("\'+a+\'")\'})+");return n}")(t,b.frag)}function j(a){a||(a=b);var d=f(a);return!t.shivCSS||k||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),l||i(a,d),a}var k,l,m="3.7.2",n=a.html5||{},o=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,p=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,q="_html5shiv",r=0,s={};!function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",k="hidden"in a,l=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){k=!0,l=!0}}();var t={elements:n.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:m,shivCSS:n.shivCSS!==!1,supportsUnknownElements:l,shivMethods:n.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=t,j(b)}(this,document);\n'; function callHTML5Shiv () {

 eval(html5shiv);

}

var pjaxCalledOnce = false; function goForwardListener (event) {

 var node = event.target;
 var url = parseURL(node.href);
 if (url === null)
   return true;
 history.pushState(null, null, node.href);
 loadPage(url);
 if (!pjaxCalledOnce) {
   pjaxCalledOnce = true;
   window.addEventListener('popstate', goBackListener);
 }
 return false;

}

function goBackListener (event) {

 var url = parseURL(document.URL);
 if (url === null)
   return;
 loadPage(parseURL(document.URL));

}

function checkURLForPJAX (url) {

 var isOutsideLink = !startsWith(href, basePath);
 if (isOutsideLink)
   return;
 var current = parseURL(document.URL);
 var next = parseURL(url);
 var isSamePage = current.path === next.path;
 if (isSamePage)
   return;
 else
   return next;

}

function parseURL (url) {

 var info = url.substr(basePath.length).split('#');
 return {
   path: info[0],
   anchor: info[1],
   fetch: function (callback) {
     var url = basePath + this.path + mediaWikiRawQuery;
     $.ajax(url).done(function (data) { callback(null, data); });
   }
 };

}

//utility functions function startsWith (lhs, rhs) {

 var isStartWith = lhs.substr(0, rhs.length) === rhs;
 return isStartWith;

}

function selectCore (from, to, str) {

 return str.split(from)[1].split(to)[0];

}

//magic "numbers" var basicStyles = [

 'http://cdnjs.cloudflare.com/ajax/libs/foundation/5.2.3/css/foundation.min.css',
 'http://ricostacruz.com/nprogress/nprogress.css',
 '/Team:HSAAHNU_Anhui/normalize.css?action=raw&ctype=text/css'

];

var basicScripts = [

 'http://code.jquery.com/jquery-1.11.1.min.js',
 'http://ricostacruz.com/nprogress/nprogress.js'

];

var PJAXSplitter = {

 start: ,
 end: 

};

var basePath = 'https://2014hs.igem.org/Team:HSAAHNU_Anhui'; var mediaWikiRawQuery = '?action=raw';

document.addEventListener('DOMContentLoaded', function () {

 cleanup();
 loadResources();
 waitForScripts();

});