Just like the posting on where to put CSS, javascript functions in a similar way.

Javascript can be written in .js files or included dynamically on the page via <script> tags or even on an item-by-item basis with things like “onclick=’doStuff()'”.

If you have certain functions or variables you need to have always available and globally accessed, put them in a shared .js file that is included on every page.  This is a great way to handle some basic Ajax calls and some other shared code that is used frequently.

If you have forms that have custom requirements before submitting, include that code right in the PHP file you’re working on as a part of the visual part of your command structure.  This will make debugging easier and you can dynamically generate that form verification based on logic that PHP knows about (such as which form elements should or should not be included based on various conditions).

Sometimes you just need to do a really simple something that is unique on a per element basis: Go ahead and add javascript right into your element as needed.  Makes it easy to debug and there’s no reason to make things more complicated than you need to.

DO NOT put all of your javascript into .js files just because you think you should.  There’s no good reason to.  Instead, look at where they fit best on their own.  Some javascript may need to be dynamically generated by PHP.  Having a static .js file is incompatible with this concept.

August 28th, 2013

Posted In: Basics

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: