Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating javascript files with .php extension

Tags:

javascript

php

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.

like image 397
Abhishek Saha Avatar asked Nov 24 '12 07:11

Abhishek Saha


People also ask

Can you have JavaScript in a PHP file?

You can execute Javascript through PHP by calling javascript code/function as a string in PHP and send it to the client browser to execute.

Can JavaScript link to PHP?

Yes possible. You can write PHP code in html and can link js also.

What extension should a file containing a PHP script have?

php file extension refers to the name of a file with a PHP script or source code that has a ". PHP" extension at the end of it. It's similar to a Word file with a . doc file extension.

How run JS file in PHP?

echo '<script type="text/javascript">jsFunction();</script>';


1 Answers

If you'd like to compile multiple Javascript files into one on the server side with PHP, you can do something like this:

<?php
// script.js
header('Content-Type: text/javascript'); // Tell browser to treat file as Javascript

$files  = array(
    'script-1.js',
    'script-2.js',
    'script-3.js'
);

foreach($files as $file){
    // Import each file
    echo file_get_contents($file).PHP_EOL;
}

Then, in your page, just reference that file as though it was a Javascript file:

...
<script src="script.php"></script>
...
like image 91
Adam Avatar answered Oct 20 '22 00:10

Adam