1

After doing a lot of reading on the subject, I realized that many developers mix javascript and php in the same file (by adding the .php extension or using other ways).

On the other hand, if I choose to separate the javascript from the php and store it in an external cacheable static file, I gain some performance advantage, but I also need to find creative ways to pass server-side data to the javascript.

For example, since I can't use a php foreach loop in the .js file I need to convert php arrays to json objects using json_encode. In other cases, I need to declare gloabl javascript variables in the original php file so I can use them in the external js file. Since server side processing is considered faster than javascript, converting to js arrays and using global vars may also be a bad idea...

The bottom line is I'm trying to understand the trade off here. Which has more impact on performance, enable caching of js files or keeping a cleaner code by avoiding global js variables and multidemnsional js arrays?

18
  • FYI no sane person would mix Javascript and PHP (HTML in between PHP code is the greatest horror mankind has seen since WW2). Commented Nov 15, 2011 at 9:07
  • Zanfa is just saying it's ugly to maintain. I reckon with the heredoc syntax you can pretty much treat your HTML-generating PHP like a HTML template, just keep your view together and your PHP functions in reusable includes/classes. Commented Nov 15, 2011 at 9:28
  • @Zanfa this is your personal opinion, not shared by the most of PHP folks. Commented Nov 15, 2011 at 10:26
  • @Lee it's heredoc that's ugly to maintain. while native HTML is the best way you can use to maintain HTML. Commented Nov 15, 2011 at 10:27
  • 1
    @Col.Shrapnel I think most PHP folks are enjoying the abstraction of the templating solution rather than any beauty. It's still tokenised HTML, no templating solution is 'Native HTML'. So that can't be the best way, can it? Commented Nov 15, 2011 at 11:52

6 Answers 6

6

are you talking about performance of the server or the browser?

my personal opinion is that given the choice between making a server slower or making a browser slower, you should always choose to let the browser be slower.

usually, "slow" means something like "takes 100ms" or so, which is not noticeable on an individual browser, but if you have a few hundred requests to a server and they're all delayed by that, the effect is cumulative, and the response becomes sluggish. very noticeable.

let the browser take the hit.

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

2 Comments

So I understand you recommend avoiding the mix if js and php in order to enable caching and making less server requests. Is that correct?
if you're going to generate JS with PHP, it should be the minimum possible. provide static functions in external files, and dynamic variables with the PHP. this is an oversimplification, obviously. if you want to really look into speed, get a copy of Steve Souders' book "High Performance Websites"
1

I think it depends on what your trying to do. My personal opinion is that it's a little bit of a pain to prevent your dynamic JavaScript from being cached.

Your static JS files need to contain your functions and no dynamic data. Your HTML page can contain your dynamic data. Either within a SCRIPT block (where you will be able to use PHP foreach), or by putting your data into the DOM where the JavaScript can read it, it can be visible (in a table) or invisible (e.g. in a comment) - depends on whether your data is presentable or not.

You could also use AJAX to fetch your dynamic data, but this will be an additional request, just like an external JS file containing the data would.

As Kae says, adding additional load onto the client would benefit your server in terms of scalability (how many users you can serve at any one time).

1 Comment

Thanks for the clear answer. I will try to use the foreach loop inside a script block as you suggest.
0

Data:

If the amount of dynamic data isn't too big and constantly changing (must not be cached by the browser), I would suggest adding it to the head of the HTML. To prevent it from polluting the global namespace, you can use either a closure or a namespace (object), to contain all related variables. Performance-wise, I don't think that in this case, there would be much difference between looping the data into JS-friendly format or handling it to the finest detail on the server (JS has become amazingly fast).

Things are a bit more complicated when the amount of data is huge (100+kbs to megabytes). In case the data is pretty much constant and cacheable, you should generate a external data file (not an actual new file, but an unique URL), which you could then include. Using a timestamp in the name or correctly set cache headers would then enable you to save the time on both server-side (generating the JS-friendly output) and client-side (downloading data) and still offer up to date data.

If you have a lot of data, but it's constantly changing, I'd still use external JS files generated by PHP, but you have to be extra careful to disable browser caching, which make your constantly changing data pretty much constant. You could also do dynamic loading, where you pull different parts of data in parallel and on demand via JS requests.

Code:

The functional part of your code should follow the explanation from before: Now to the question whether JS should be inlined to the HTML or separated. This depends highly on code, mostly of it's length and reusability. If it's just 20 lines of JS, 10 of which are arrays, etc that are generated by PHP, it would make more sense to leave the code inside the HTML, because HTTP requests (the way how all resources are delivered to the client) are expensive and requesting a small file isn't necessarily a great idea.

However, if you have a bit bigger file with lots of functionality etc (10s of kbs), it would be sensible to include it as a separate .js file in order to make it cacheable and save it from being downloaded every time.

And there's no difference in PHP or JS performance, whether you include the JS inside templates/PHP or separately. It's just a matter of making a project manageable. Whatever you do, you should seriously look into using templates.

6 Comments

You can put PHP into a Javascript file, by simply calling the Javascript file 'file.php' and including it with <script src= as normal.
Well, duuuh. Never said that you couldn't. I was simply explaining different aspects of the question, so if that's what the -1 was for, you can remove it.
I am using codeigniter, so there is already an MVC structure. Either way, there must be some PHP inside the HTML in order to pass data from the database to the view. If I want to manage external js files, there must also so be some little js code inside the html in order to assign those php vars or to simply call the external js function. So it's not completely doable to avoid mixing of the 3 at all costs. The last part of your answer makes sense and can help avoiding server load. thanks
you are missing the big picture here.
Okay, it's morning so I misunderstood the original problem slightly:P To be perfectly clear, there doesn't HAVE to be PHP inside the template, JS in the template or PHP in JS. Keeping the 3 is perfectly doable. I reread your question and fix my answer too.
|
0

After doing a lot of reading

That's what you are probably doing wrong.

There are many people fond on writing articles (and answers on Stackovervlow as well) who has a very little experience and whose knowledge is based... on the other articles they read!
Don't follow their bad example.

Instead of "a lot of reading" you have to do a lot of profiling!.

First of all you have to spot the bottlenecks and see if any of them are caching related.
Next thing you have to decide is what kind caching your system require.
And only then you can start looking for the solution.

Hope it helps.

6 Comments

You assume that I believe and implement everything I read which is not true. What I said is that many developers mix JS and PHP and this is a simple fact. And exactly for the reason that I dont believe everything I read, I posted this question in a very popular forum, hoping to find answers from experienced developers who proved to give smart answers for other questions as well. I hope my intentions are clearer now. Either way, thanks for answering
Nope, your intentions are still unclear. Just because you have no idea if you need any caching at all. But of course, asking strangers who have no idea of your server is better than profiling it. Keep going.
I need caching, otherwise I wouldn't ask this question because there would be no trade off here. If I didnt need cahching, I would go with the approach of mixing php with js and avoiding the hassle of finding a way to pass server data to external js files
Some facts are true, independent from specific server configurations. There's a so-called 80/20 rule yuiblog.com/blog/2006/11/28/performance-research-part-1 which explains exactly why your server configuration might not matter as much (or at all). Some truths, like decreasing number of HTTP requests and making everything as cacheable as possible are universal.
In addition, ALWAYS do research on a subject that you are not fully comfortable with, to be sure that you know what to look for. I've done some serious optimization to my own JS projects, but I'm sure I myself wouldn't have come up with a number of them. Of couse, everything needs to be fine tuned to your application and that's where profiling and benchmarking is crucial.
|
0

QDF to your problem is to send the data in a hidden HTML table.

HTML tables are easy to generate in php and easy to ready in JavaScript.

Comments

0

I have a solution when the situation is passing info from php to js and keep most js outside the main php file. Use the js objects or js functions. You make some code that needs data from php. When the page loads some small js code is generated from php. Like:

<script type="text/javascript">
a(param1, param2, param3)
</script>

and it's done. The server indicates param1, param2 and param3 directly in the code.

The function is inside a .js file that is cached. With this you reduce the server's upload and the time for the page js to start. The client's code is a bit slower but you win for the time to download and the server becomes faster.

3 Comments

thanks, I used this method before and passed a php array (with db data) to the js function by writing (with your example): a(<?php json_encode($arr);?>). By the way, if I use this method can I make that PHP array be cached as well if I know the data change frequency is rare in this case?
This way you may you are unable to use caching for that. You can, however, use the Storage interface and a parameter in the function telling that the info is the same and the browser may use the cached version of the info and that if the cached version does not exist to execute an AJAX request for that info (check other answers for the AJAX method to solve this)
By Stroage interface are you referring to HTML5 Web Storage?

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.