Skip to content

Instantly share code, notes, and snippets.

@DC3
Created October 24, 2015 07:26
Show Gist options
  • Select an option

  • Save DC3/ae5e10016f3283c46e70 to your computer and use it in GitHub Desktop.

Select an option

Save DC3/ae5e10016f3283c46e70 to your computer and use it in GitHub Desktop.
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