Marty
Marty

Reputation: 39456

Is using PHP to collate multiple JavaScript files going to be faster than including them all separately?

I know that serving multiple small files is much slower than serving one larger file, this is why it's good to use a single CSS document as well as sprite sheets. I've also tried to include as much JavaScript into the smallest amount of files as I can for a while now, to avoid multiple requests from the viewer for more files, but having a variety of clearly different tasks in the same document gets confusing and messy.

I've been wondering if using PHP to combine a larger amount of JavaScript files into a single file and then serving that with the content-type set to application/x-javascript would get around this problem.

I'm assuming that because the server manages retrieving those files, the viewer will only request a single file. I do however have minimal knowledge around how the server will deal with that though, and if it's going to end up being the same issue just the other way around (and end up just as slow). I have a feeling that because the JavaScript is all hosted in the same place as the PHP that it shouldn't be the case.

Will I receive the same benefit of only having a single JavaScript file if I actually have multiple files and serve them as a single document via PHP?

Upvotes: 2

Views: 95

Answers (1)

Mark Reed
Mark Reed

Reputation: 95267

You get the benefit of a single HTTP request to retrieve the JS file, so the browser experience will be faster (at low traffic levels, at least), but your server will be working much harder to execute the PHP code instead of just serving up static files. That may be fine if you don't get much traffic, but for best results you should combine this technique with a cache layer in front of the PHP.

Upvotes: 5

Related Questions