PHP vs JavaScript For Dynamic HTML Pages

Eric picture Eric · May 24, 2011 · Viewed 54.7k times · Source

Typically when I put together dynamically generated HTML markup, I've been using PHP to store the information and then looping through that to create elements on the page. One example is navigation; create an array of objects and then loop through them to echo the markup. This helps out a lot for times that I might have to make minor (or major) changes during development or maintenance.

Lately I've been wondering if I should use JavaScript to do this instead. Same principle, but using addElement.

Just wanted to get some opinions on this; pros, cons, php vs js, seo considerations, etc.

Thanks folks!

Answer

Quentin picture Quentin · May 24, 2011

Doing it client side means:

  1. Doing it in lots of different environments instead of a single one
  2. Having it break whenever a user comes along without JS (for whatever reason)
  3. Having it fail to work for the vast majority of bots (including search engines)
  4. Investing development time in converting all your logic
  5. Requiring the browser to make additional requests to the server, slowing down load times

When deciding if you should do something client side instead of server side, as a rule of thumb ask yourself two questions:

  1. Would the user benefit from getting instant feedback in response to them doing something? e.g. An error message for improper data in a form they are trying to submit. If so, then doing it client side would be beneficial.
  2. Can it be done server side? If so, do it server side first as it is more reliable (and for non-cosmetic things, harder to interfere with). Build on things that work.