Remove javascript comments within php file - javascript

I have a javascript file, myjs.php, that is generated on the server and delivered to the browser with a header.
Header("content-type: application/x-javascript; charset=utf-8");
The file is large and contains a lot of comments that are echoed within the js sections:
echo " // comments /* comments */ etc.
I appreciate that, if necessary, I could rewrite the php so that all comments were within php sections.
Is there a way, within PHP, to remove these comments at runtime so that they are not part of the file that is delivered to the browser, either by minifying or by some other means?

You can use tool such as UglifyJS from a PHP wrapper. There are packages to handle it, like UglifyPHP. After your file is generated, run the minifier on it, which will also strip comments:
use UglifyPHP\JS;
$js = new JS(['myjs.php']);
$js->minify('myjs.js', [
'comments' => false,
]);
In combination with ob_start(), ob_get_contents(), ob_end_clean() and using raw file stream as input you can achieve desired result.
Update:
Added this on demand by OP, if one haven't got possibility to use anything other than pure LAMP stack.
Here's a reference on how to remove single- and multiline PHP comments from a file:
Regex to strip comments and multi-line comments and empty lines
And here's working universal solution:
Best way to automatically remove comments from PHP code
This do the trick.

Related

How does php know when interpret and when to output?

I recently tried including JavaScript using PHP as such:
<?php include 'iife.SomeFile.js';?>
I did not expect it to work, b.c. I thought it would try to interpret the JS as PHP, but instead it just included the file as I asked it.
Is it b.c. I simply omitted the <?php tag that it chose to output the file as text.
Makes me wonder if I can include pretty much any type of file I want.
Also, makes the purpose of SSI seem redundant.
Because this is a valid PHP file:
<html>
...
<script>
var foo = 'bar';
</script>
You may notice that there's no PHP at all in this file, yet it's still valid. That's because PHP was designed as an embedded language to be used in HTML, delimited by the <?php ?> tags. PHP passes anything that's not in those tags through as is.
Also, makes the purpose of SSI seem redundant.
The existence of one language does not make another redundant. Many languages overlap with many other languages in what they can do. Doesn't mean we should all be using just one language. For one, SSI is a lot more lightweight than a full-blown PHP instance if all you want is to include a file.
PHP includes work the same way includes for languages such as C. They simply include or insert the file at that point.
It's just like typing in that entire file yourself where you put the include.
PHP code is executed on the server side. JavaScript is executed on the client side (except with node.js)
The include statement is used to include PHP code. You can use it to include a php lib file in your code.

JS, PHP, Html File Conventions

I have 3 questions, but I think the first 2 are very simple, so I'll ask them all here.
I normally work in C++ with SQL (and sometimes with VBA), and I'm trying to figure out the basics of JS, PHP & HTML (I've mostly got the jist of HTML and CSS).
I have 5 different reference books plus the net, but one thing I can't seem to find anything about are the file exts (.js, .php, .html).
From my tests I have come to realize that you can usually run JS scripts in other file types, but PHP seems to require the .php ext.
So the questions are:
Do I always have to use *.php for PHP scripting?
In a SINGLE file, can I delay PHP execution by simply putting the code into a function?
eg
<?php
function test() {echo "hello world";}
//as opposed to:
echo "hello world";
?>
When using multiple files, are there any compelling reasons to (or not to) always put scripts in their corresponding file types (e.g. JS in *.js). Obviously this would make it easier to understand / read, especially as it grows BUT can this create problems?
No, you can use any extension you want. Even if you want, don't use extension at all. But then, tell your server what interpreter to use when he founds he has to parse a *.wtf file. I mean, you're running a the script "file.wtf" from the command line you can do it like this:
$>php file.wtf
but if the script is to be parsed by your favorite web server (like Apache) because it is part of (say) a web page, then you have to configure it to interpret .wtf files with the PHP library.
By simply putting it in a function:no. But you really want to delay execution, use the sleep function
Just what you said: You can mix html and javascript code in your php files, but that is very messy.

Include javascript files content in ob_start buffer

I am currently working on the translation of a website.
To perform this translation easily, I created a .csv file containing the matches between the two languages (japanese->english).
Then, this file is parsed with PHP, and ob_start() is called on the page in order to replace wanted strings.
Here is the script :
function lang_modify($buffer){
require('get_messages.php');
for($i=0; $i<count($messages); $i++){
$buffer = str_replace($messages[$i][0], $messages[$i][1], $buffer);
}
return $buffer;
}
$buffer = ob_start('lang_modify');
This script works perfectly on php/html files. However, ob_start does not read javascript files so I was wondering if someone knows a way to include javascript files into the output buffer so that the ob_start() function will replace the words found in javascript as well.
Someone adviced me to do search something with the AddFile statement (.htaccess), but I don't know at all how could I use this to do what I want.
Does anyone have a clue ?
What you are facing here, is a Separation of Concerns issue.
Your translation is generated from PHP.
And yet, your javascript displays and (sometimes) generates those messages.
How do i fix this?
1) Make sure your translations comes from one single source, ideally from PHP
2) Use an i18n js library to process your translations. I suggest: https://airbnb.github.io/polyglot.js/
3) If you are using Polyglot, make sure that your PHP translations are being generated into a js file, which is then loaded based on localisation.
Polygot will translate your default messages into internationalized ones.
In short:
Enable Modularity - Administer(CRUD) all your translations in PHP. Storing them in a database
would be ideal
Decouple JS from translation - Polygot will only provide the translated messages to your views(HTML).

PhpStorm Inject PHP language into JavaScript files

How can I add automatic language injection for PHP into JavaScript files?
When I add some PHP code into JavaScript the whole syntax highlighting messes up and I got a ton of errors.
I tried to add language injection with ALT+ENTER but I don't get PHP in my list of injections:
This won't work. The reason that it cannot be done is that when you load the javascript file in your browser, the PHP code will just appear as plain text, rather than actually be ran to produce the result that you want.
Just to reiterate, you cannot inject PHP code into Javascript files, what you can do however, is have inline javascript, within a file that can handle PHP. For example, if you want the variable contents, you'd have your JS file like follows:
$(function() {
loadSomething(varNameHere);
});
Then somewhere in the main body of the main, file somewhere that PHP can be ran, you can have this.
?>
<script> var varNameHere = "<?=$somePhp;?>"; </script>
<?php
While not ideal, this is a base example of how it'd work. Hope that helped.

Having multiple css and javascript files

I have multiple jquery, javascript and css files loading in my head. I want a way to simplify and fasten up the process of loading these files. I also have different javascripts in the head and above the /body tag. I have looked into requirejs and headjs but I find it very complicated and don't know if I can load my stylesheets with this framework.
The size of the site is quite large due to it being a scroll to section site. My question is, is there a way to load my css, javascript files, jquery code and javascript in a simple fast way and if this is possible with headjs or requirejs can someone give me an example on how to do this in an easy way as I am just so confused as their API is not easy to follow for beginners.
Thanks.
The simplest first step you can take is to reduce the number of HTTP requests. Typically, each request spends as much time queued as it does downloading, so you can reduce all of the queue time by having a single CSS file and a single JavaScript file.
So your first step is to combine the files in the same order you include them and then include just the one combined CSS file and the one combined JavaScript file.
Next Steps
Once you've done this, you can follow it up with:
Minification. This is a process that makes your file size smaller, for example by removing unnecessary white-space and by compressing variable names.
Move script includes to just before </body>. This gives the illusion of speed as the visible page will load before the script is requested, which makes the page appear faster to the user.
To easily merge CSS :
Make a php file,
<?php
header('Content-type: text/css');
header("Vary: Accept-Encoding");
header("Cache-control: public");
header("Last-Modified: ".gmdate("D, d M Y H:i:s"). " GMT");
$cssstyles = '';
$lines = file("file1.css");
foreach ($lines as $line_num => $line)
$cssstyles .= trim($line);
$lines = file("file2.css");
foreach ($lines as $line_num => $line)
$cssstyles .= trim($line);
$lines = file("file3.css");
foreach ($lines as $line_num => $line)
$cssstyles .= trim($line);
echo preg_replace('/\/\*(.+?)\*\/|[\s]*([:;{},>])[\s]*/','$2',$cssstyles);
?>
Replace file1, file2, file3 by each of your files.. You can pass a GET parameter to get different CSS for different pages.
And then call your file as stylesheet with :
<link rel="stylesheet" href="yourFile.php" />
You can use js/css combine techniques to reduce requests from server
https://code.google.com/p/minify/
There are other ways as well like host external files on other server. (CDN technique)
This will also help you:
http://sixrevisions.com/web-development/site-speed-performance/
You can try to compress/minify it and merge it together.
Javascript: Google CLosure Compiler (online)
or minify: Minify
There are thing that you can do for a better performance like:
Merge you small CSS or JS files to one file to reduce number of requests.
Use GZip on your server to reduce size of your resources. (for example jQuery minified version is about 90kb but after enabling GZip on your webserver it will become 30k)
Setting up GZip for your server is vwery simple.
Use tools that will minify your codes. You can save up a lot after minification your code. there are many online tools like this one which I always use.
It's a while that I put my javascript codes at the end of my page right before closing body tag. You may not be able to run jQuery code for example in middle of your HTML but the advantages of loading JS at the end are more than this one disadvantage.
Have a look at these articles.You need to learn the optimization technique to increase the efficiency of code loading.
load-javascript-faster
faster-page-loads-bundle-your-css-and-javascript
speed-up-your-javascript-load-time
One of the best things you can do is minify your files that you put live. There are various free services that do this, such as http://gruntjs.com or http://jsmini.com
A step further, if your site uses PHP, then you can setup some files to load conditionally.
On my personal sites... I use PHP to set the variable $title equal to whatever the simplified page name is, for example "home" or "gallery".
I then include two files into my <head> one for conditional CSS files, and one for conditional JS files...
Then I for example there are 3 javascript files and two css files that are ONLY needed for the gallery page. So I have a simple IF statement in the two conditional files mentioned above like this:
if ($title == "Gallery") {
echo "<script src=\"afile.js\"></script>";
}
This way, these particular files never get loaded unless they are actually required. There are ofcourse certain CSS sheets and javascript files which are required site-wide, in which case I enter those into the <head> just like you would normally, and I always load my "conditional files" BELOW their respective counterparts.
I believe that what you are looking for is called bundling and minification. You can use it to conacatenate all javascript files in one big file, and also minimize its size. The same thing apply to css files.
There are a lot of different solutions depending on the platform that you are using for developement.
For example:
http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification
You can reduce the size of your webpage by following two things
1)Compress your Files :
Genrally js/Css files are written with lots of white spaces for readability and thus they occupy more bandwith. After Compression you can generally gain 30-50% reduction in the size of Javascript files and 40-70% reduction in Css files.
2)Combine more than one files:
Each time a file is sent from server to client it occupies request response headers and some other informations. This can be reduced by combining files.
In case of related files of javascript and css files you can combine multiple js/css files in one files.
you can use online tools which compresses as well as join multiple css/js files into one
like
jsCompressor and CSS Compressor

Categories

Resources