Created
November 8, 2012 00:14
-
-
Save jonathantneal/4035559 to your computer and use it in GitHub Desktop.
Update the visible-but-unfocused tab's page, styles, and scripts without ever pressing refresh.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (document) { | |
function forEach(array, callback) { | |
for (var i = 0, l = array.length; i < l; ++i) { | |
callback(array[i]); | |
} | |
} | |
function refreshElements() { | |
// prevent refreshing if the document is hidden or the page is focused | |
if (document.hidden || document.mozHidden || document.msHidden || document.oHidden || document.webkitHidden || (document.hasFocus && document.hasFocus())) return; | |
forEach(document.querySelectorAll("html,link[rel],script[src]"), function (element) { | |
// prevent cross-domain requests | |
if (String(element.href || element.src || location).indexOf(location.protocol + "//" + location.host) != 0) return; | |
var xhr = new XMLHttpRequest; | |
xhr.onreadystatechange = function () { | |
if (xhr.readyState > 1) { | |
xhr.lastModified = xhr.lastModified || +new Date(xhr.getResponseHeader("Last-Modified")); | |
element.dataset.lastModified = element.dataset.lastModified || xhr.lastModified; | |
// if the source is newer than the last request | |
if (xhr.lastModified > element.dataset.lastModified) { | |
if (xhr.readyState == 4 && xhr.status == 200) { | |
// if refreshing the document | |
if (element.nodeName == "HTML") { | |
document.write(xhr.responseText); | |
document.close(); | |
return; | |
} | |
// if refreshing an element | |
element.dataset.lastModified = xhr.lastModified; | |
// clone the element | |
for (var clone = document.createElement(element.nodeName), i = 0, attr; attr = element.attributes[i]; ++i) { | |
clone.setAttribute(attr.name, attr.value); | |
} | |
element.parentNode.replaceChild(clone, element); | |
element = clone; | |
} | |
} else { | |
xhr.abort(); | |
} | |
} | |
}; | |
xhr.open("GET", element.href || element.src || location, true); | |
xhr.setRequestHeader("Cache-Control", "no-cache"); | |
xhr.setRequestHeader("Pragma", "no-cache"); | |
xhr.send(null); | |
}); | |
} | |
// poll the document at 5 frames/second | |
setInterval(refreshElements, 200); | |
})(document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment