Skip to content

Instantly share code, notes, and snippets.

@nojvek
Last active September 25, 2015 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nojvek/16a393d3d2c741b443bd to your computer and use it in GitHub Desktop.
Save nojvek/16a393d3d2c741b443bd to your computer and use it in GitHub Desktop.
LiveReload CSS
// Watch for changes and auto-reload
// CSS changes get auto injected, js changes reload current page
var pollInterval = 2; // check every 2 seconds
var jsMap = {"powerbi.js":null, "powerbicommon.js":null};
var cssMap = {"powerbi.css":null, "powerbicommon.css": null};
function getLastModifiedTime(url, callback) {
$.ajax({
type: "HEAD", // HEAD only gives headers, a lot faster
url: url,
complete: function (xhr, status) {
lastMod = xhr.getResponseHeader('Last-Modified');
if (!lastMod) console.error("Couldn't find ", url);
callback(new Date(lastMod));
}
});
}
function checkCSSForUpdate(file) {
var cssNode = $("link[href *= '" + file + "']");
var url = cssNode.attr("href");
var paramIndex = url.indexOf("?");
if (paramIndex > 0) url = url.substr(0, paramIndex);
getLastModifiedTime(url, function (lastMod) {
if (!cssMap[file]) cssMap[file] = lastMod; // save initial mod time
else if (cssMap[file] < lastMod) { // if newer file then inject update
cssNode.attr("href", url + "?t=" + new Date().getTime());
cssMap[file] = lastMod;
console.log(url, "updated", lastMod);
}
});
}
function checkJSForUpdate(file) {
var url = $("script[src *= '" + file + "']").attr("src");
getLastModifiedTime(url, function (lastMod) {
if (!jsMap[file]) jsMap[file] = lastMod;
else if (jsMap[file] < lastMod) {
location.href = location.href; //reload
}
});
}
function checkForUpdates() {
for (var i = 0, jsFiles = _.keys(jsMap), len = jsFiles.length; i < len; ++i) {
checkJSForUpdate(jsFiles[i]);
}
for (var i = 0, cssFiles = _.keys(cssMap), len = cssFiles.length; i < len; ++i) {
checkCSSForUpdate(cssFiles[i]);
}
}
checkForUpdates();
setInterval(checkForUpdates, pollInterval * 1000);
console.log("Watching", _.keys(jsMap), _.keys(cssMap));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment