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.
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.
Yes possible. You can write PHP code in html and can link js also.
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.
echo '<script type="text/javascript">jsFunction();</script>';
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>
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With