Compress Javascript Files - javascript

I have a little situation here and in-spite of searching a lot - am not getting to a solution.
I am loading Javascript Files in the footer of my page as below
<script type='text/javascript' src='/scripts/jScrollPane.js?ver=1.0'></script>
<script type='text/javascript' src='/scripts/common.js?ver=1.0'></script>
<script type='text/javascript' src='/scripts/preload.js?ver=1.0'></script>
<script type='text/javascript' src='/scripts/scroller.js?ver=1.0'></script>
<script type='text/javascript' src='/scripts/easing.js?ver=1.0'></script>
<script type='text/javascript' src='/scripts/jquery.backgroundPosition.js?ver=1.0'></script>
All I want to do is instead of including the above files - just include one compressed file which is made by compressing all the above files.
<script type='text/javascript' src='/scripts/one.js'></script>
I have tried a lot of options and each time there is an error in the file generated.
Is there a solution where I upload all files - get one compressed file and it works without an error?
Is is possible that these files themselves are missing ending ;'s - the reason why there are errors?
What can I do to come to an alternative here.
Cheers!

I would start of by running my code through JSLint http://www.jslint.com/ for instance, so that you can identify and solve any JS-errors.

I suggest something like Minify: http://code.google.com/p/minify/
Minify is a PHP5 app that helps you follow several of Yahoo!'s Rules
for High Performance Web Sites.
It combines multiple CSS or Javascript files, removes unnecessary
whitespace and comments, and serves them with gzip encoding and
optimal client-side cache headers.

Is there a solution where I upload all files - get one compressed file and it works without an error?
Yes, assuming that your files are setup correctly.
Is is possible that these files themselves are missing ending ;'s - the reason why there are errors?
Exactly, the files you minify must support the removing of line breaks. Missing semicolons are the biggest problem.

Paste each file into the Closure Compiler Service. Keep the optimization level at "Simple".
Correct any error you might get. Watch out for missing semicolons at the end of the file, as these do not trigger an error.
Concatenate the results in one file.
Done.

Related

JS errors when changing hosts

Previously I was using managed hosting but have recently been testing a VPS server setup running CentOs with Virtualmin.
I have moved over a website which works absolutely fine on the managed hosting, but moving it to the VPS gives me multiple JS errors. For some reason, it doesn't seem to be loading any of the JS scripts. When I replace the scripts with CDN links, it all works fine again.
I've checked the directory permissions and they're set the same as the previous hosting, I can also access and read each file using website.com/js/bootstrap.min.js for example. The only difference is the JS directory itself is "Forbidden". I'm not sure if that makes a difference when I can read the actual files?
My question is, why could this be happening if JS runs similar to HTML and works fine when using the CDN scripts? Also, what is the meaning of the random IDs contained in the JS SRC scripts right before text/javascript shown below, could this be the cause?
<script src="js/jquery-3.2.1.min.js" type="7fb652456240e11add396d8d-text/javascript"></script>
<script src="js/bootstrap.min.js" type="7fb652456240e11add396d8d-text/javascript"></script>
<script src="js/jquery.slicknav.min.js" type="7fb652456240e11add396d8d-text/javascript"></script>
<script src="js/owl.carousel.min.js" type="7fb652456240e11add396d8d-text/javascript"></script>
<script src="js/jquery.magnific-popup.min.js" type="7fb652456240e11add396d8d-text/javascript"></script>
<script src="js/circle-progress.min.js" type="7fb652456240e11add396d8d-text/javascript"></script>
<script src="js/mixitup.min.js" type="7fb652456240e11add396d8d-text/javascript"></script>
<script src="js/instafeed.min.js" type="7fb652456240e11add396d8d-text/javascript"></script>
<script src="js/masonry.pkgd.min.js" type="7fb652456240e11add396d8d-text/javascript"></script>
<script src="js/main.js" type="7fb652456240e11add396d8d-text/javascript"></script>
<script src="js/rocket-loader.min.js" data-cf-settings="7fb652456240e11add396d8d-|49" defer></script></body>
</html>
It seems that you didn't put JQuery back on your new hosting.
There are a few clues:
'unexpected token': jquery uses $
'jQuery is not defined'
It could also be that you put jQuery in a different location than where it was on your managed hosting. It could also be that it's still pointing to your old hosting.
If that doesn't work, try removing the text before text/javascript (although I doubt that's the issue, considering it worked on your old hosting). Also, Javascript's mime type is application/javascript.
Try checking those. That should fix your problem.
I can also access and read each file using
website.com/js/bootstrap.min.js for example. The only difference is
the JS directory itself is "Forbidden".
This doesn't make sense. Either the folder is forbidden or it is not.
If you can access that folder through the browser url, then clearly it is not forbidden. If you get a 'Forbidden' message in your browser, then obviously the folder is forbidden and you found the problem.
My question is, why could this be happening if JS runs similar to HTML
and works fine when using the CDN scripts?
Go to the network tab in your browser and check the http status that you receive in the browser for the resource that you request, i.e. jQuery in this case. The error that bootstrap throws is probably just a consequence of the fact that jQuery isn't loaded. I guess there must be a dependency.
If not, in the absolute worst case you can load the unminified version of the script that throws, and debug the problem based on the original source code.
The reason why it works for a CDN is obviously because these domains allow you public access to the resource it hosts, if not you wouldn't be able to get it, and it is sort of the point of using a CDN.
Btw, you should use a CDN, there is no clear argument as for why you shouldn't for these common libs.
Also, what is the meaning of the random IDs contained in the JS SRC
scripts right before text/javascript shown below, could this be the
cause?
I assume that you mean in the type, not in the src attribute of the html.
This is your code:
<script src="js/jquery-3.2.1.min.js" type="7fb652456240e11add396d8d-text/javascript"></script>
This doesn't make sense. If anything, they look like generated hashes which often happen when you load chunks of Javascript asynchronously.
It must be framework related, although I have no idea what framework you're currently using. I don't know if you're using SSR, CSR, templating library, bundling library etc.
But it should be clear that something generates this string for you. You need to check your template, what generates your template, and either way, remove the type altogether if you can. It's really useless in that spot.

How to combine all js external script tag to one?

I have to combine all the script tag to one for page speed purpose. I tried merging all the js files but its causing errors with jquery. Following are few scripts i have used.
<script src="/index_files/jquery_002.js" type="text/javascript"></script>
<script src="/index_files/jquery_003.js" type="text/javascript"></script>
<script src="/index_files/mootools-core.js" type="text/javascript"></script>
<script src="/index_files/core.js" type="text/javascript"></script>
<script src="/index_files/respond.js" type="text/javascript"></script>
Please can anyone help me with this.
There are many ways to go about this...
Google's closure compiler is a nice online version
http://closure-compiler.appspot.com/home
If you use Grunt there are many modules for you, I always use requireJS so I use the JS optimizer that comes with it.
Some Name:
Yui compressor
Google Closure compiler
UlgifyJS (pretty sure it combines files too)
If you give me some more info about your project I could help you further.
You could do this multiple ways:
Combine the files using some sort of tool. Closure Compiler is great, or look at something like webpack or rollup for more complex applications
Utilize HTTP/2 to make it equivalent. All modern browsers support HTTP/2 out of the box. You can use this to your advantage by doing server push, which will reduce the number of requests made to the server. Read more here. Note that while this doesn't technically combine the files, it combines them into one request.
Inline them into your body. This would make them one file, but it's generally a bad idea. (looking at you AMP) As for why see #4
Don't! As caching becomes more and more common, combining scripts, especially library scripts, together, can be wasted bandwidth, as User Agents will likely already have jQuery cached. This can be used in conjunction with HTTP/2 for great effect

How to combine multiple scripts into one script in JSP?

Here are my scripts
<script type="text/javascript" src="../js/btgAportion.js"></script>
<script type="text/javascript" src="../js/tab.js"></script>
script type="text/javascript" src="../js/jquery_calc.js"></script>
<script type="text/javascript" src="../js/jquery_onload.js"></script>
<script src="../js/jquery-latest.js"></script>
<script src="../js/collapsible.js"></script>
They all are in common js folder
I want to combine all these scripts into one script to reduce HTTP requests
There are a number of approaches. Edit, if you're going to downvote me, let me at least say, this tool of mine is a java tool for aggregating javascript files together for exactly the purpose you want:
http://damonsmith.github.io/js-class-loader/
Otherwise, if you want to roll your own JSP based solution, you can create a scripts.jsp which reads each one and just concatenates them all together into the output, then use that scripts.jsp inside your HTML script tag. It's probably easier for small sites than my over-engineered tooling.
You can use https://github.com/dfsq/compressJS.sh shell script to compress multiple JS files to one.
From official ReadMe:
Very simple bash script which compresses javascript files with Google
Closure Compiler and then make a single file of them. Reduce file
sizes and save bandwidth with just one simple command.
Reduce number of HTTP round-trips by combining multiple JavaScript resources into one.
https://developers.google.com/speed/pagespeed/service/CombineJavaScript
compress javascripts by using : http://jscompress.com/

Use wildcard in src attribute of <script> tag?

Ok, stupid question and I don't think it's possible but, I have this markup at the top of my .aspx page...
<%--Third Party Libraries, Plugins, Extensions --%>
<script src="Libraries/Raphael/Raphael.js" type="text/javascript"></script>
<script src="AutoComplete/jquery.autocomplete.js" type="text/javascript"></script>
<script src="Libraries/jQuery/1.4.2/jquery.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.core.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.widget.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.mouse.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.draggable.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.droppable.js" type="text/javascript"></script>
Wouldn't it be nice if I could replace that with this...
<%--Third Party Libraries, Plugins, Extensions --%>
<script src="Libraries/Raphael/Raphael.js" type="text/javascript"></script>
<script src="AutoComplete/jquery.autocomplete.js" type="text/javascript"></script>
<script src="Libraries/jQuery/1.4.2/jquery.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.*.js" type="text/javascript"></script>
ie use the * as wildcard.
Obviously as this is JS I could just throw all those scripts into one big script and load that but I don't really fancy doing that.
Anyone else have a technique for tidying up masses of script refs? Or do we just live with it?
As far as I know this is not possible, simply because, the browser would need to know exactly what files to request.
The browser would essentially have to brute force your server with requests hoping to get lucky.
I'd suggest using Google's closure compiler to merge all similar, if not all, javascript files into a single file. It will be slightly large, but would cut down on http request.
With some profiling you could find a balance between which files are needed most commonly and speed.
UPDATE (from comments)
I'm generally reluctant to offer adding a new javascript library to solve the issue of too many javascript libraries :) Plus this just seemed like the more straight forward solution. Current we use the Google closure API to compress and merge all our javascript and CSS and build time with ANT. Works a charm. This can also be done to some extent direct with apache2 virtual host/htaccess (see html5boilerplate.com) for examples and limitations
Nope, not in the way you're thinking of. You could do something that's similar if you're using JavaScript loaders (e.g. RequireJS or LabJS), since you can then condense each file into an array and loop through them, or, if you're feeling ambitious cook up some protocol between the front and back ends to support this.
Nonetheless, this is not recommended as it's not easy to maintain. If your problem with combining the files into a single one is with the effort, then JS minifiers (e.g. UglifyJS or Closure Compiler) may solve your problem.
Actually, as somebody else may have mentioned, you could add your own script file in there and do something like add the paths to an array, loop through it calling getScript for each item.
$.getScript('ajax/test.js', function() {
alert('Load was performed.');
});
ie use the * as wildcard.
No. Well, not unless you want to configure your server to pass a URL which includes a * character through a script that resolves it and bundles up all the JS on the fly.
Obviously as this is JS I could just throw all those scripts into one big script and load that but I don't really fancy doing that.
It's a good solution. Generally you would want to do this as part of a build script for the site, and throw in a call to a minifier at the same time.
I would omit type="text/javascript"
The "type" attribute is required in HTML 4, but optional in HTML5.
But I still think that merging src is impossible (as of HTML5 and CSS3)
You could just copy the contents of all the jquery.ui.* files into one file. As an added bonus, your pages would load slightly faster.

Keeping my jQuery code away from the html files

I am learning jQuery and have a created several plug ins.
Unfortunately due to my company's coding practices they want all javascript code to be extract out to js files. This for me poses two challenges:
Can i extract the actual $(document).ready(..) call to a js file? So far with my limited knowledge I have not figured if this at all possible. If not, I welcome any suggestions to make this cleaner and more acceptable way to include this code.
There are too many javascript includes for each asp.net page header since I may be using several plugins. Is there a way to reduce the potential costly server trips that I would need to make each time I need these files?
Any suggestions, corrections are greatly appreciated
thanks
1. Absolutely.
Just add a script reference to your html like this:
<script type='text/javascript' src='js/yourfile.js'></script>
Then just start your .js file with
jQuery(function() {
foo;
...
bar;
});
or any other shortcut ways of starting the jQuery code block.
2. You should run your scripts through something like Minify before sending them off to the user. This will combine the files and pack them in nicely, so that they take up less space.
Using $(document).ready () in an external javascript file is fine - it will work exactly the same :) In fact - not only will it work, but it is good practice as it helps to seperate the content (HTML) from the behaviour (Javascript).
In response to your section question - you can combine all of your plugins into a single javascript file and link to that one inside the <head>. You could also try minifying the scripts, although this is normally a bit overkill until the site goes live.
When I use jQuery, I normally use this kind of structure:
<html>
<head>
<!-- html tags such as title, link, meta etc -->
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript" src="/path/to/plugin.js"></script>
<!-- more plugins included if required -->
</head>
<body>
<!-- html here -->
<!-- script is the last thing before the ending body tag (increases performance) -->
<script type="text/javascript" src="/path/to/your_jQuery_code.js"></script>
</body>
</html>
I think worrying about server trips for javascript includes is premature optimization. Do you have any evidence that these pages are loading slowly? The browser should be caching the javascript files.
If you do have evidence that this is a problem, you could
-combine the jquery code and any plugins into one file
-write an .net content handler to do this for you (probably overkill)
Then you can add a custom js file per page to handle page specific properties.
You can most definitely put your document.ready and all other JavaScript code in an external file.
Typically I have 2 calls - one for jQuery itself, and one minified global.js file that combines and minifies all of my individual files.
Personally, I like to use front end blender for this, but there are many other options available as well.
there's nothing wrong w/putting the document.ready call in an external file. in fact, it's what i do to separate my js from my html. if you're concerned about certain functions running on certain pages, you may sift through them with a
var path = window.location.pathname;
if (path == "/yourdir/yourpage.html") {
//do something for this page only
}
or you can just include certain files only on certain pages.

Categories

Resources