Browse Source

Refactor JS

Make DOM ready code reusable and send SVG XHR before DOM is ready, we only need to wait for the DOM to inject the elem.
pm2
Luke Childs 9 years ago
parent
commit
cfdb8ead60
  1. 64
      public/assets/enhancements.js

64
public/assets/enhancements.js

@ -1,5 +1,18 @@
(function() { (function() {
// Run callback when DOM is ready
function DOMReady(fn) {
// Run now if DOM has already loaded as we're loading async
if(['interactive', 'complete'].indexOf(document.readyState) >= 0) {
fn();
// Otherwise wait for DOM
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
// Feature detection results // Feature detection results
var supports = {}; var supports = {};
@ -23,19 +36,8 @@
) == 'http://www.w3.org/2000/svg'; ) == 'http://www.w3.org/2000/svg';
})(); })();
// Add ios class to body on iOS devices // Check required features for favourite nodes
function iosBodyClass() { if(supports.localStorage && supports.inlineSVG) {
if(
/iPad|iPhone|iPod/.test(navigator.userAgent)
&& !window.MSStream
&& document.body.classList
) {
document.body.classList.add('ios');
}
}
// Favourite nodes
function favouriteNodes() {
// Get heart SVG // Get heart SVG
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
@ -45,32 +47,28 @@
// Create heart SVG elem // Create heart SVG elem
var div = document.createElement('div'); var div = document.createElement('div');
div.innerHTML = xhr.responseText; div.innerHTML = xhr.responseText;
this.heart = div.firstChild; var heartEl = div.firstChild;
// Inject heart into DOM // Inject heart into DOM
this.title = document.querySelector('h2.node-title'); DOMReady(function() {
if(this.title) { var titleEl = document.querySelector('h2.node-title');
this.title.insertBefore(this.heart, this.title.firstChild); if(titleEl) {
} titleEl.insertBefore(heartEl, titleEl.firstChild);
}
});
}); });
xhr.send(); xhr.send();
} }
// Check if DOM has already loaded as we're loading async // Add ios class to body on iOS devices
['interactive', 'complete'].indexOf(document.readyState) >= 0 DOMReady(function() {
? init() if(
: document.addEventListener('DOMContentLoaded', init); /iPad|iPhone|iPod/.test(navigator.userAgent)
&& !window.MSStream
// When DOM is ready && document.body.classList
function init() { ) {
document.body.classList.add('ios');
// Check for iOS
iosBodyClass();
// Check required features for favourite nodes
if(supports.localStorage && supports.inlineSVG) {
favouriteNodes();
} }
} });
})(); })();

Loading…
Cancel
Save