3

I am working on a large php mysql CMS. I did a decent job organizing my server side code with includes, objects, etc. Now that I have started to jazz up the front end with things like form validation and image sliders I am starting to accumulate a mess of tiny javascript/jquery functions. Most of these are under 5 lines and are only used on one page each.

Is it bad practice/lazy to throw all of these into a functions.js file, include it in my header then call myJavaScriptFunction() in the page where I need it? If so what is a better approach?

2 Answers 2

2

Is it bad practice/lazy to throw all of these into a functions.js file, include it in my header then call myJavaScriptFunction() in the page where I need it?

This would work, but be careful you're not loading large amounts of useless functions in each page. For example, if you have 30 Javascript functions related to manipulating a Google Map and you have only one page which deals with the Google Maps API, you'll be wasting a lot of time loading these useless functions if you include them on each page.

Sign up to request clarification or add additional context in comments.

1 Comment

In that case I should do something like generalFunctions.js and googMapFunctions.js and include the latter on the page that contains the Google Map to be manipulated.
0

If they are only used on one page, why put them in a universal file. This is a good time to weigh the pros and cons.

Pros:

  1. Browser caches the javascript file, the first page request is slightly slower, every next one is slightly faster.
  2. Slightly simpler HTML, because the javascript is kept in a separate file.
  3. Separate file, so syntax highlighting!

Cons:

  1. A ton of useless javascript code is loaded every time you load a page

To me, it seems like this is something that you shouldn't do, but it really depends on how your large JavaScript code is, and how easy it is to put a <script> tag into your head.

1 Comment

Sorry I should reword that sentence. I meant a majority of the tiny functions are used on one page each. Not all on one page. But either way, the pros and cons still stand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.