rewrite: add footer deferrred scripts, plus middwlare for sending node

envs to jade
This commit is contained in:
Tyler Renelle 2013-08-28 12:53:55 -04:00
parent de5837462a
commit 7fba8db654
7 changed files with 76 additions and 61 deletions

View file

@ -194,27 +194,7 @@ setupGrowlNotifications = (model) ->
if captures > args
statsNotification '<i class="icon-chevron-up"></i> Level Up!', 'lvl'
module.exports.resetDom = (model) ->
window.DERBY.app.dom.clear()
window.DERBY.app.view.render(model, window.DERBY.app.view._lastRender.ns, window.DERBY.app.view._lastRender.context);
# Note, Google Analyatics giving beef if in this file. Moved back to index.html. It's ok, it's async - really the
# syncronous requires up top are what benefit the most from this file.
googleAnalytics = (model) ->
if model.flags.nodeEnv is 'production'
window._gaq = [["_setAccount", "UA-33510635-1"], ["_setDomainName", "habitrpg.com"], ["_trackPageview"]]
$.getScript ((if "https:" is document.location.protocol then "https://ssl" else "http://www")) + ".google-analytics.com/ga.js"
amazonAffiliate = (model) ->
if model.get('_loggedIn') and (model.get('_user.flags.ads') != 'hide')
$.getScript('//wms.assoc-amazon.com/20070822/US/js/link-enhancer-common.js?tag=ha0d2-20').fail ->
$('body').append('<img src="//wms.assoc-amazon.com/20070822/US/img/noscript.gif?tag=ha0d2-20" alt="" />')
googleCharts = ->
$.getScript "//www.google.com/jsapi", ->
# Specifying callback in options param is vital! Otherwise you get blank screen, see http://stackoverflow.com/a/12200566/362790
google.load "visualization", "1", {packages:["corechart"], callback: ->}
module.exports.app = (appExports, model, app) ->
loadJavaScripts(model)
@ -233,16 +213,3 @@ module.exports.app = (appExports, model, app) ->
#for some reason selecting a date doesn't fire a change event on the field, meaning our changes aren't saved
model.at(ev.target).set 'date', moment(ev.date).format('MM/DD/YYYY')
###
External Scripts
JS files not needed right away (google charts) or entirely optional (analytics)
Each file getsload asyncronously via $.getScript, so it doesn't bog page-load
These need to be handled in app.on('render'), see https://groups.google.com/forum/?fromgroups=#!topic/derbyjs/x8FwdTLEuXo
###
$.getScript('//checkout.stripe.com/v2/checkout.js')
unless (model.get('_mobileDevice') is true)
$.getScript("//s7.addthis.com/js/250/addthis_widget.js#pubid=lefnire")
googleCharts()
googleAnalytics(model)
amazonAffiliate(model)

View file

@ -0,0 +1,44 @@
"use strict";
habitrpg.controller("FooterCtrl", ['$scope', '$rootScope', 'User', '$http',
function($scope, $rootScope, User, $http) {
/**
External Scripts
JS files not needed right away (google charts) or entirely optional (analytics)
Each file gets loaded async via $.getScript, so it doesn't bog page-load
*/
$scope.deferredScripts = function(){
// Stripe
$.getScript('//checkout.stripe.com/v2/checkout.js');
// Amazon Affiliate
if ($rootScope.authenticated() && User.user.flags.ads !== 'hide') {
$.getScript('//wms.assoc-amazon.com/20070822/US/js/link-enhancer-common.js?tag=ha0d2-20').fail(function() {
$('body').append('<img src="//wms.assoc-amazon.com/20070822/US/img/noscript.gif?tag=ha0d2-20" alt="" />');
});
}
// Google Analytics, only in production
if (window.env.NODE_ENV === 'production') {
window._gaq = [["_setAccount", "UA-33510635-1"], ["_setDomainName", "habitrpg.com"], ["_trackPageview"]];
$.getScript(("https:" === document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js");
}
// Scripts only for desktop
if (!window.env.IS_MOBILE) {
// Add This
$.getScript("//s7.addthis.com/js/250/addthis_widget.js#pubid=lefnire");
// Google Charts
$.getScript("//www.google.com/jsapi", function() {
google.load("visualization", "1", {
packages: ["corechart"],
callback: function() {}
});
});
}
}
}])

View file

@ -1,35 +1,33 @@
splash = (req, res, next) ->
isStatic = req.url.split('/')[1] is 'static'
unless req.query?.play? or req.getModel().get('_userId') or isStatic
res.redirect('/static/front')
else
next()
nconf = require('nconf')
_ = require('lodash')
module.exports = (req, res, next) ->
# splash = (req, res, next) ->
# isStatic = req.url.split('/')[1] is 'static'
# unless req.query?.play? or req.getModel().get('_userId') or isStatic
# res.redirect('/static/front')
# else
# next()
view = (req, res, next) ->
model = req.getModel()
## Set _mobileDevice to true or false so view can exclude portions from mobile device
model.set '_mobileDevice', /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(req.header 'User-Agent')
model.set '_nodeEnv', model.flags.nodeEnv
next()
_.defaults (res.locals.habitrpg ?= {}),
NODE_ENV: nconf.get('NODE_ENV')
IS_MOBILE: /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(req.header 'User-Agent')
#CORS middleware
allowCrossDomain = (req, res, next) ->
#CORS middleware
res.header "Access-Control-Allow-Origin", (req.headers.origin || "*")
res.header "Access-Control-Allow-Methods", "OPTIONS,GET,POST,PUT,HEAD,DELETE"
res.header "Access-Control-Allow-Headers", "Content-Type,Accept,Content-Encoding,X-Requested-With,x-api-user,x-api-key"
# wtf is this for?
if req.method is 'OPTIONS'
res.send(200);
else
next()
return res.send(200);
translate = (req, res, next) ->
model = req.getModel()
# Set locale to bg on dev
#model.set '_i18n.locale', 'bg' if process.env.NODE_ENV is "development"
# translate = (req, res, next) ->
# model = req.getModel()
# # Set locale to bg on dev
# #model.set '_i18n.locale', 'bg' if process.env.NODE_ENV is "development"
# next()
next()
module.exports = { splash, view, allowCrossDomain, translate}

View file

@ -1,12 +1,12 @@
nconf = require('nconf')
express = require 'express'
router = new express.Router()
_ = require('lodash')
router.get '/', (req, res) ->
res.render 'index',
title: 'HabitRPG | Your Life, The Role Playing Game'
NODE_ENV: nconf.get('NODE_ENV')
env: res.locals.habitrpg
router.get '/partials/tasks', (req, res) -> res.render 'tasks/index'
router.get '/partials/options', (req, res) -> res.render 'options'

View file

@ -3,7 +3,6 @@ http = require("http")
path = require("path")
app = express()
nconf = require('nconf')
middleware = require("./middleware")
require('./config') # Setup configurations
require('./errors')
@ -40,6 +39,7 @@ app.use express['static'](path.join(__dirname, "/../public"))
app.use express.errorHandler() if "development" is app.get("env")
# Custom Directives
app.use(require('./middleware'))
app.use(require('./routes/pages').middleware)
app.use('/api/v1', require('./routes/api').middleware)
app.use(require('./controllers/deprecated').middleware)

View file

@ -3,6 +3,9 @@ html
head
title HabitRPG | Your Life The Role Playing Game
script(type='text/javascript').
window.env = !{JSON.stringify(env)};
// CSS
link(rel='stylesheet', href='/bower_components/bootstrap/docs/assets/css/bootstrap.css')
link(rel='stylesheet', href='/bower_components/bootstrap/docs/assets/css/bootstrap-responsive.css')
@ -46,6 +49,7 @@ html
!= js('controllers/tasksCtrl')
!= js('controllers/taskDetailsCtrl')
!= js('controllers/userAvatarCtrl')
!= js('controllers/footerCtrl')
//webfonts
link(href='//fonts.googleapis.com/css?family=Lato:300,400,700,400italic,700italic', rel='stylesheet', type='text/css')

View file

@ -1,4 +1,4 @@
footer.footer
footer.footer(ng-controller='FooterCtrl')
.container
.row
.span3
@ -41,7 +41,7 @@ footer.footer
li
a(target='_blank', href='http://www.reddit.com/r/habitrpg/') Reddit
.span3
if (NODE_ENV=='production')
if (env.NODE_ENV=='production')
h4 Social
.addthis_toolbox.addthis_default_style(addthis:url='https://habitrpg.com', addthis:title='HabitRPG - Gamify Your Life')
table
@ -68,3 +68,5 @@ footer.footer
button.btn(x-bind='click:cheat') Insta Level
li
button.btn(x-bind='click:reset') Reset Level
div(ng-init='deferredScripts()')