rmmoul
rmmoul

Reputation: 3217

include javascript with php or client side script tags

I'm not sure how to check out which is better, so I was wondering if anyone had some insight.

For javascript files, is it faster (or better) to use the script tags in the html and let the browser download the script from the server, or is it faster to use php to include the javascript file with the html when it's served to the user. The php method would decrease the number of get requests, but increase the file size. The argument I could think of against the php include, is client side caching, but I wasn't sure what kind of impact each method would have on a larger scale.

Anyone have some insight?

Upvotes: 1

Views: 383

Answers (1)

Alan Geleynse
Alan Geleynse

Reputation: 25139

Both of these options will require the user to download the content, but one requires 2 connections and the other requires 1.

This means that in general it will be faster to put it inline with an include or similar.

However, that assumes that the javascript is required to load the page.

If you can load most of the page without it, you can put the <script> tag near the bottom and let the user download the page and process it before loading the script.

It also depends if you have all your content on a single page with AJAX requests or if you load a lot of pages with the same javascript. If you are sharing it, it is best to take advantage of the caching, but if it is a single page it is better to inline it.

Upvotes: 1

Related Questions