Created
October 24, 2015 07:26
-
-
Save DC3/ae5e10016f3283c46e70 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| doc = document | |
| $$ = doc.querySelectorAll.bind(doc) | |
| NodeList::__proto__ = Array:: | |
| genParam = -> '?_=' + Date.now() | |
| getXHR = (url) -> | |
| xhr = new XMLHttpRequest | |
| xhr.open 'GET', url | |
| xhr | |
| getPath = (url) -> | |
| a = doc.createElement 'a' | |
| a.href = url | |
| [a.protocol, '//', a.host, a.pathname].join('') | |
| # NOTE: this helper need CORS support | |
| # plz check that before your use this | |
| # recommand use `http-server --cors` | |
| class CSSRefresh | |
| attrName: 'data-last-modified' | |
| constructor: (interval = 3e3) -> | |
| @print = console.info.bind(console, 'CSSRefresh:') | |
| links = $$('link') | |
| @print "find #{links.length} nodes." | |
| start = => links.forEach @checkUpdate | |
| @tId = setInterval start, interval | |
| @print 'start watching.' | |
| checkUpdate: (node) => | |
| last = node.getAttribute(@attrName) | |
| url = getPath(node.href) | |
| setLastAttr = (val) => node.setAttribute @attrName, val | |
| refresh = (val) => | |
| return if val is +last | |
| setLastAttr(val) | |
| node.setAttribute 'href', url + genParam() | |
| @print "#{url} is refresh." | |
| cb = if last then refresh else setLastAttr | |
| @getLastModified(url, cb) | |
| getLastModified: (url, cb) -> | |
| xhr = getXHR(getPath(url) + genParam()) | |
| xhr.onload = -> | |
| last = new Date(xhr.getResponseHeader('last-modified')) | |
| time = +last | |
| #console.log last, time | |
| xhr.onload = null | |
| xhr = null | |
| cb(time) | |
| xhr.send() | |
| stop: -> | |
| @print 'stop watching.' | |
| return unless @tId | |
| clearInterval @tId | |
| @tId = null | |
| root = exports ? this | |
| root.CSSRefresh = CSSRefresh |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment