Where to add code to run on page refresh?


#1

I have code setup to run on Meteor.startup and on certain routes for iron router, but when I push code and the page refreshes the scripts don’t run. Anyone know how to do this properly?


#2

Any code in Meteor.startup() should run again - the page is actually refreshed when the new code is pushed. Do you have a simple code sample where this doesn’t happen?


#3

Yep you’re right, the code does run there, but I realized I originally took it out cause I need to know the current path. Do you know of anyway to get the current path or route name (something like Router.current().route.getName()) that works in Meteor.startup()?


#4

I think you would probably want to run your code inside iron router’s after hook instead of Meteor.startup():

Router.onAfterAction(function () {
  // in here, the router has already determined the current route and everything
});

See more here: https://github.com/iron-meteor/iron-router/blob/devel/Guide.md#hooks


#5

Thanks!! Yep you’re spot on. I just spent a bunch of time figuring it out and go it just as I saw you posted it.


#6

Also, for anyone that may read this. I am setting a class for the body and ended up using onAfterAction and this reactive body class add on https://github.com/meteor-london/body-class.


#7

Off topic, but why the need to set a class for the body?
Is it to help organise your CSS a bit by having a class selector based on the current route?


#8

One use case I came across was setting the page background based on the route.


#9

I used it for page background, but also I have a separate theme for the admin and front end of my site. The front end has a sticky footer so it requires body specific stuff and the theme is one I bought and all the code is based off a body class since it has some styles on the background etc.


#10

Also sometimes when you have to integrate a third party theme/template, you get a complete mess that you need to keep as close to the original as possible (to be future-proof) and you just got to have id’s and classes on body.

I happen to have had one lousy 10-minute task yesterday for converting a one-page site to a meteor project for some added interactivity that turned out to be a 10-hour collosal headache. The design implemented javascript that loads css externally and selectively depending on browser/device/size etc with some silly initialization logic that changed the dom as well as an id and some classes on body.

Spent the first 9 hours trying to tame the whole thing into a proper meteor file structure, gave up, and then used iron router’s onAfterAction hooks within which I implemented all the javascript that the site needed.