0

My application's front-end currently uses a single merged/minified javascript file for performance reasons. It's a convenient setup, but I have run into a problem. Individual pages have their own startup code in $(function()), but because the site's combined javascript is referenced on every page, all of the startup functions execute on every page, which is completely unintended.

The only solution I have come up is to place a conditional in each startup function to execute only if certain pieces of data can be found in the page's container. For example:

$(function() {
  if($('title').text()=='some title') {
  // do something
  }
}

The above function would run only if the page's title is 'some title', thus preventing it from running on other pages (assuming they have different titles, of course). This strategy would likely work for the entire site, but it seems hacky and unsafe. Does anyone have a better solution?

emagdne
  • 527
  • 4
  • 11

1 Answers1

0

If you have a 1000 pages then that's 999 functions you are downloading even though you don't need them. Pull out the individual stuff into their own js files. Then for each page you will only pull down two js files (the core on and the page specific one). Then I would take it a step further and implement caching on imgs and js files so they are not pulled down or even checked to see if they were modified thus saving many network trips. But then when you push out changes you must force the users to re-download the files, do this by changing the directory structure with each "push" or build".

Example: yoursite/javascript/jan01build/allYourJsFiles

Then implement caching (say for a year) on the top-level javascript folder like this... https://stackoverflow.com/a/16753140/3112803

Now if you watch the network traffic by using F12 in Chrome you should be seeing "status 200" and "size - from cache" for the js files. This means a network trip wasn't even done to see if it was modified (a 304 status).

Then when you change your code and do another "push" or "build" you will have to force the users to get the new files, do so by simply changing the directory to...

Example: yoursite/javascript/feb01build/allYourJsFiles

(repeat all this with images)

Community
  • 1
  • 1
gfrobenius
  • 3,987
  • 8
  • 34
  • 66