Team:HSAAHNU Anhui/inject.js

From 2014hs.igem.org

(Difference between revisions)
(analyze anchor)
(refactor)
Line 2: Line 2:
  * Basically this script will do the following thing:
  * Basically this script will do the following thing:
  * Remove old styles.
  * Remove old styles.
-
  * Apply common stylesheets.
+
* Remove old script tags.
 +
  * Apply common stylesheets. (Bootstrap, NProgress)
 +
* Apply common scripts. (jQuery, Bootstrap, NProgress)
  * Update jQuery.
  * Update jQuery.
  * move inner HTML of main tag to body tag for clarity.
  * move inner HTML of main tag to body tag for clarity.
  * Clean up script tags in head tag for debugging purpose.
  * Clean up script tags in head tag for debugging purpose.
  * Set up PJAX for better performance.
  * Set up PJAX for better performance.
-
  * Use PJAX.complete to set up page specific things.
+
  * Complete page specific jobs.
  */
  */
-
function removeOldStyles () {
+
var commonStylesheets = [
-
  function removeStyleNodes () {
+
  'http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css',
-
    var styleNodes = document.head.getElementsByTagName('style');
+
  'http://ricostacruz.com/nprogress/nprogress.css',
-
    while (styleNodes.length !== 0) {
+
  '/Team:HSAAHNU_Anhui/normalize.css?action=raw&ctype=text/css'
-
      document.head.removeChild(styleNodes[0]);
+
];
-
    }
+
-
  }
+
-
   function removelinkStylesheetNodes () {
+
var commonScripts = [
-
     var linkNodes = document.head.getElementsByTagName('link');
+
   'http://code.jquery.com/jquery-1.11.1.min.js',
-
     var nonStylesheetLinksCounter = 0;
+
  'http://ricostacruz.com/nprogress/nprogress.js'
-
     var iter = 0;
+
];
-
     while (linkNodes.length !== nonStylesheetLinksCounter) {
+
 
-
       var node = linkNodes[iter];
+
function cleanup () {
-
       if (node['rel'] === 'stylesheet')
+
  function removeNodesFromHead (tag, constriant) {
 +
    constriant = constriant ? constriant
 +
                            : function () { return true; };
 +
     var nodes = document.head.getElementsByTagName(tag);
 +
     var failedCounter = 0;
 +
     var iterator = 0;
 +
     while (node.length !== failedCounter) {
 +
       var node = nodes[iterator];
 +
       if (constriant(node))
         document.head.removeChild(node);
         document.head.removeChild(node);
       else {
       else {
-
         nonStylesheetLinksCounter ++;
+
         failedCounter ++;
-
         iter ++;
+
         iterator ++;
       }
       }
     }
     }
-
   }
+
   };
-
   removeStyleNodes();
+
   removeNodesFromHead('style');
-
   removelinkStylesheetNodes();
+
   removeNodesFromHead('script');
-
}
+
  removeNodesFromHead('link', function (node) {
-
 
+
     var isStylesheet = node.rel === 'stylesheet';
-
function applyCommonStyles () {
+
     return !isStylesheet;
-
  var stylesheetURLs = [
+
-
    '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'
+
-
  ];
+
-
 
+
-
  stylesheetURLs.forEach(function (url) {
+
-
     var tag = document.createElement('link');
+
-
    tag.href = url;
+
-
    tag.rel = 'stylesheet';
+
-
     document.head.appendChild(tag);
+
   });
   });
-
}
 
-
 
-
function updateJQuery () {
 
-
  var tag = document.createElement('script');
 
-
  tag.src = 'http://code.jquery.com/jquery-1.11.1.min.js';
 
-
  document.head.appendChild(tag);
 
-
}
 
-
function relocateMainDocument () {
 
   var main = document.body.getElementsByTagName('main')[0];
   var main = document.body.getElementsByTagName('main')[0];
   document.body.innerHTML = main.innerHTML;
   document.body.innerHTML = main.innerHTML;
 +
}
 +
 +
function applyCommonResources () {
 +
  function applyResources (factory, urls) {
 +
    urls.forEach(function (url) {
 +
      var node = factory(url);
 +
      document.head.appendChild(node);
 +
    });
 +
  };
 +
 +
  applyResource(function (url) {
 +
    var node = document.createElement('link');
 +
    node.href = url;
 +
    node.rel = 'stylesheet';
 +
    return node;
 +
  }, commonStylesheets);
 +
  applyResource(function (url) {
 +
    var node = document.createElement('script');
 +
    node.src = url;
 +
    return node;
 +
  }, commonScripts);
}
}
Line 80: Line 90:
$(document).ready(function () {
$(document).ready(function () {
-
   removeOldStyles();
+
   cleanup();
-
   applyCommonStyles();
+
   applyCommonResources();
-
  updateJQuery();
+
-
  relocateMainDocument();
+
   waitForJQueryToBeUpdated();
   waitForJQueryToBeUpdated();
});
});
-
function cleanUpScriptTags () {
+
function fetchData (href, callback) {
-
   var scriptNodes = document.head.getElementsByTagName('script');
+
   var team = '/Team:HSAAHNU_Anhui';
-
   while (scriptNodes.length !== 0) {
+
   var query = '?action=raw&ctype=text/css';
-
     document.head.removeChild(scriptNodes[0]);
+
  var url = team + href.path + query;
-
   }
+
  $.ajax(url).done(function (data) {
 +
     callback(null, data);
 +
   });
}
}
function loadNewPage (href) {
function loadNewPage (href) {
-
   alert(JSON.stringify(href));
+
   NProgress.start();
 +
  fetchData(href, function (err, data) {
 +
    alert('done');
 +
    NProgress.done();
 +
  });
}
}
Line 131: Line 145:
     return false;
     return false;
   });
   });
 +
}
 +
 +
function completePageSpecificJobs () {
 +
  var info = thisPageInfo;
 +
  var isInfoObject = info instanceof Object;
 +
  if (!isInfoObject)
 +
    return false;
 +
 +
  info.title ? $('title')[0].innerText = info.title : null;
}
}
function resumeInitAfterJQueryUpdated () {
function resumeInitAfterJQueryUpdated () {
-
  cleanUpScriptTags();
 
   setupPJAXListener();
   setupPJAXListener();
 +
  completePageSpecificJobs();
}
}

Revision as of 10:20, 30 May 2014

/*

* Basically this script will do the following thing:
* Remove old styles.
* 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 removeNodesFromHead (tag, constriant) {
   constriant = constriant ? constriant
                           : function () { return true; };
   var nodes = document.head.getElementsByTagName(tag);
   var failedCounter = 0;
   var iterator = 0;
   while (node.length !== failedCounter) {
     var node = nodes[iterator];
     if (constriant(node))
       document.head.removeChild(node);
     else {
       failedCounter ++;
       iterator ++;
     }
   }
 };
 removeNodesFromHead('style');
 removeNodesFromHead('script');
 removeNodesFromHead('link', function (node) {
   var isStylesheet = node.rel === 'stylesheet';
   return !isStylesheet;
 });
 var main = document.body.getElementsByTagName('main')[0];
 document.body.innerHTML = main.innerHTML;

}

function applyCommonResources () {

 function applyResources (factory, urls) {
   urls.forEach(function (url) {
     var node = factory(url);
     document.head.appendChild(node);
   });
 };
 applyResource(function (url) {
   var node = document.createElement('link');
   node.href = url;
   node.rel = 'stylesheet';
   return node;
 }, commonStylesheets);
 applyResource(function (url) {
   var node = document.createElement('script');
   node.src = url;
   return node;
 }, commonScripts);

}

var JQueryLoadingTime = 0; function waitForJQueryToBeUpdated () {

 //16 seconds is long enough.
 var isLoadFailed = JQueryLoadingTime >= 32;
 if (isLoadFailed)
   alert('One component of this page failed to load. Please refresh!');
 var isJQueryUpdated = $.fn.jquery === '1.11.1';
 if (isJQueryUpdated)
   resumeInitAfterJQueryUpdated();
 else {
   JQueryLoadingTime ++;
   setTimeout(waitForJQueryToBeUpdated, 500);
 }

}

$(document).ready(function () {

 cleanup();
 applyCommonResources();
 waitForJQueryToBeUpdated();

});

function fetchData (href, callback) {

 var team = '/Team:HSAAHNU_Anhui';
 var query = '?action=raw&ctype=text/css';
 var url = team + href.path + query;
 $.ajax(url).done(function (data) {
   callback(null, data);
 });

}

function loadNewPage (href) {

 NProgress.start();
 fetchData(href, function (err, data) {
   alert('done');
   NProgress.done();
 });

}

function startsWith (lhs, rhs) {

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

}

function analyzeAnchor (href) {

 var basePath = 'https://2014hs.igem.org/Team:HSAAHNU_Anhui';
 var isOutsideLink = !startsWith(href, basePath);
 if (isOutsideLink)
   return false;
 var current = document.URL.substr(basePath.length).split('#');
 var next = href.substr(basePath.length).split('#');
 var isSamePage = current[0] == next[0];
 if (isSamePage)
   return false;
 return {
   path: next[0],
   anchor: next[1]
 };

}

function setupPJAXListener () {

 $("a").click(function (event) {
   var node = event.target;
   var href = analyzeAnchor(node.href);
   if (href === false)
     return true;
   loadNewPage(href);
   return false;
 });

}

function completePageSpecificJobs () {

 var info = thisPageInfo;
 var isInfoObject = info instanceof Object;
 if (!isInfoObject)
   return false;
 info.title ? $('title')[0].innerText = info.title : null;

}

function resumeInitAfterJQueryUpdated () {

 setupPJAXListener();
 completePageSpecificJobs();

}