Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
prerender script used for generating static pages for
fs = require 'fs'
webpage = require 'webpage'
page = webpage.create()
renderedUrls = 0
totalUrls = 0
# Taken from
# Converted into coffee
waitFor = (testFx, onReady, timeOutMillis) ->
maxtimeOutMillis = (if timeOutMillis then timeOutMillis else 5000) #< Default Max Timout is 3s
start = new Date().getTime()
condition = false
interval = setInterval(->
if (new Date().getTime() - start < maxtimeOutMillis) and not condition
# If not time-out yet and condition not yet fulfilled
condition = ((if typeof (testFx) is "string" then eval_(testFx) else testFx())) #< defensive code
unless condition
# If condition still not fulfilled (timeout but condition is 'false')
console.log "'waitFor()' timeout"
phantom.exit 1
# Condition fulfilled (timeout and/or condition is 'true')
# console.log "'waitFor()' finished in " + (new Date().getTime() - start) + "ms."
(if typeof (onReady) is "string" then eval_(onReady) else onReady()) #< Do what it's supposed to do once the condition is fulfilled
clearInterval interval #< Stop this interval
, 250) #< repeat check every 250ms
prerenderUrls = (urls) ->
for url in urls
((url) ->
subPage = webpage.create() url, ->
# Wait until our container has been made visible from angularjs
# This only happens once all ajax requests are finished
# Returning false here will indicate that the page is not ready yet
return subPage.evaluate ->
if document.getElementsByClassName('container').length == 0
return false
return document.getElementsByClassName('container')[0].offsetParent?
, ->
# Strip all javascript tags out of the page. We don't want them here.
content = subPage.content.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
# To quickly get the path of the url, we generate a tag and go over the href api
el = document.createElement('a')
el.href = url
path = "./dist#{el.pathname}.prerender.html"
# In case the website is a root page (a.k.a and not
if el.pathname == '/'
path = "./dist/prerender.html"
fs.write(path, content, 'w+')
renderedUrls++ "Prerendered '#{url}' to '#{path}'"
)(url) '', ->
jsonSource = page.plainText
resultObject = JSON.parse(jsonSource)
totalUrls = resultObject.length
# Watcher to auto close phantom after all urls have been rendered
if totalUrls == renderedUrls "Prerendered #{renderedUrls} urls."
, 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment