Cam
Cam

Reputation: 970

Given the choice, is it better to construct DOM elements using JQuery or PHP

As the title suggests, I'm looking for an answer to a best practice question,

Is it better to construct DOM elements using JQuery or PHP. backend or frontend.

To give some context, My PHP loop builds page elements like so;

<div id='content'>
     <div id='el1'></div>
     <div id='el2'></div>
     <div id='el3'></div>
     <div id='el4'></div>
</div>

my Jquery script rearranges the DOM like so;

<div id='content'>
     <div class='wrapper'>
          <div id='el1'></div>
          <div id='el2'></div>
     </div>
     <div class='wrapper'>
          <div id='el3'></div>
          <div id='el4'></div>
     </div>
</div>

The actual task im working on is small, almost as nominal as this example. Would there be any benefit in rewriting the PHP?

thanks, Cam

Upvotes: 1

Views: 145

Answers (5)

iWantSimpleLife
iWantSimpleLife

Reputation: 1954

My answer would be to go with the simplest solution. just do it all in one place for such a small solution. otherwise if something go wrong you need to debug two location.

I still remember last time i had a student writing php codes that generates javascripts based on an array. And the javascript will generate the web page on the client end. It was a horrible mess of spaghetti code, and he spent most of the semester just trying to figure out the codes.

Keep things simple...

Upvotes: 0

calebds
calebds

Reputation: 26228

If there is no DB or user-input related condition to be met, just do it with PHP. There is no sense changing the DOM with jQuery if it's known at the outset what the markup should be. You'd be arbitrarily elongating your HTML generation pipeline.

Upvotes: 3

Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53603

Any benchmark I did on several of systems I developed (small, no more than few dozen hits a second) it is much much more fast to construct the DOM with php.
My instinct tellms that on very BIG sites heavy with JS it still would be faster to build on server side and just cache it.

Upvotes: 0

jcreamer898
jcreamer898

Reputation: 8189

When given a choice, I'd choose using jQuery. This takes the load off of the server and let's the user see that something is happening immediately rather than waiting for the server to do it's job.

When building your DOM elements with jQuery, I'd use something like http://mustache.github.com/ or http://documentcloud.github.com/underscore/

These libraries will clean up your jQuery code and keep things nicely separated.

Upvotes: 1

whichdan
whichdan

Reputation: 1897

For something this small, the difference is really minimal, as long as you're not concerned about your users having JS disabled.

Upvotes: -1

Related Questions