Is there any way of including a .js file in HTML allowing the server to first interpret it (before downloading to the client) using php?
If you need your php file to have a .js extension, that is possible in your server configuration.
Sure, most easily by making it a
<script> define1 = <?php echo YOUR_DEFINE1; ?> define2 = <?php echo YOUR_DEFINE2; ?> </script> <script src="....."> // This script can now use define1 and define2
Not tested, but it probably works:
Try to give the script
.php as file extension.
You can do this on a server level too. Say you're using apache, you can add this line to your configuration (even your .htaccess will do):
AddType application/x-httpd-php .js
You could also do that with css or even plain ol' html pages.
I'm sure other server software have similar capabilities.
The client does not care if the script file ends in .js, .php or whatever, just about the mime type and the contents.
You could also use Apache directives, perhaps in a .htaccess file, to tell it to process a certain .js file as PHP, or direct requests for filename.js to filename.php, though it's not necessary.
file.php you'll also want to output the correct header, before outputting anything you should have the following:
EDIT: As @Tony_A pointed out, it should be
<script> global_one = '<?php echo $global_one; ?>';</script>
Quick example ;) If you put this in your html
global_one variable will be available to all js files.
©2020 All rights reserved.