Skip to content

Instantly share code, notes, and snippets.

@reggi
Last active August 29, 2015 14:01
Show Gist options
  • Save reggi/cca7b5b5898a1388ea7d to your computer and use it in GitHub Desktop.
Save reggi/cca7b5b5898a1388ea7d to your computer and use it in GitHub Desktop.

Whats the best way to have certain JavaScript run on certain pages?

The two methods i've used are kind of similar. I've set up identifiers on the page that describe what page type it is. For instance if you have pages and articles as a template type. and you have about (a page) and How great JavaScript is (an article). Then I would have something like the following.

<script>
var template = "page";
var handle = "about";
</script>
<script>
var template = "article";
var handle = "How great JavaScript is";
</script>

When you start using things like browserify and requirejs then global variables can get messy. I wised up and started using hidden input tags that specify these variables in HTML.

<input type="hidden" name="template" value="page">
<input type="hidden" name="handle" value="about">
<input type="hidden" name="template" value="article">
<input type="hidden" name="handle" value="How great JavaScript is">

These would be within the HTML somewhere, and most-likley converted from some server-side variable.

This would all funnel into certain functions that would run on certain pages / articles versus all pages / articles.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment