Creating javascript files with .php extension

javascript, php

Solution

Most browsers can use 2 or more simultaneous connections to load resources. So keeping the javascript in separate files may allow for browsers to fully utilize all the connections. You should include the `<script>` tags as late in your HTML as possible, so that the content of the page gets written before any JS even starts loading.

One advantage of using PHP would be to gzip the JS files to reduce their size.

If the size of the javascript files is small, say < 100 KB, it may very well be faster to include a number of them in one PHP script. But if the javascript files were larger, like 500 KB, it could be faster to keep them separate.

Experimentation and tuning will help you find your answer. There is no universal truth here.

Problem

I have been writing javascript functions in separate .js files. In my last project, the number of javascript files were more and so loading of the page was slower because number of requests were more. So for experimental purpose, i converted few .js files with .php extension and added them with include statements. This way the loading time performance was better. There are lot of advantages of writing javascript in .php files. I can access the php variables and easily pass them to javascript. My doubt here is that, are there any disadvantages of writing javascript in .php files and then including them ? What i understand is that when a page loads, it calls the javascript files and parallelly executes the php part. So we write onload functions.

Original source