I have searched the following and it seems no one evan asks about, so I assume there is something facepalm dumb about it:
In a php file
... php code
?><script type="text/javascript> <?php include js/filename.js ?></script>
<?php
... php code
It seems what you're trying to do is bundle your JS into your HTML output. There are in fact several use cases for this, but they don't come up often. For example, I had a web application that would load on game consoles which had no cache. As a micro-optimization, I'd just bundle all the scripts and CSS into the HTML to reduce the number of HTTP requests.
Generally speaking though, there are downsides to this. Suppose you want to use that same JavaScript on multiple pages. Where the script could have been loaded on Page A, cached, and then immediately available for Page B, now you have to load the whole thing again for Page B. Also, don't forget that proxy servers cache static resources well. If you're creating pages dynamically, those probably aren't going to be cached, even though the JavaScript could be.
Now, onto the bundling technique... what you're doing is facepalm indeed. By using include(), you're telling PHP to execute the contents of that file as if it were PHP. That's not a PHP file (I assume anyway), that's JavaScript. It's unlikely, but if <?php were to end up in that file, you're going to end up executing code you didn't intend to execute server-side. What's worse is that you're wasting CPU by having PHP look for its tokens. readfile() is what you'd want instead, which would pass through the contents of that file.
Other things to be aware of are escaping and such. You're now using a plain JS file in the context of HTML. Caution is needed.
Best to use an existing bundler tool for this. I don't have any specific recommendations at the moment... I haven't found one in PHP I particularly like.
Related
I was thinking about creating script that would do the following:
Get all javascripts from JS directory used on server
Combine all scripts to one - that would make only one request instead of multiple
Minify combined script
Cache the file
Let's say that the order in which the files need to be loaded is written in config file somewhere.
Now when I load myexamplepage.com I actually use jQuery, backbone, mootools, prototype and few other libraries, but instead of asking server for these multiple files, I call myexamplepage.com/js/getjs and what I get is combined and minified JS file. That way I eliminate those additional requests to server. And as I read on net about speeding up your website I found out that the more requests you make to server, the slower your web become.
Since I'm pretty new to programming world I know that many things that I think of already exists, I don't think that this is exception also.
So please list what you know that does exactly or similar to what I described.(please note that you don't need to use any kind of minifiers or third party software everytime you want your scripts to be changed, you keep original files structure, you only use class helper)
P.S. I think same method could be used for CSS files also.
I'm using PHP and Apache.
Rather than having the server do this on-the-fly, I'd recommend doing it in advance: Just concatenate the scripts and run them through a non-destructive minifier, like jsmin or Google Closure Compiler in "simple" mode.
This also gives you the opportunity to put a version number on that file, and to give it a long cache life, so that users don't have to re-download it each time they come to the page. For example: Suppose the content of your page changes frequently enough that you set the cache headers on the page to say it expires every day. Naturally, your JavaScript doesn't change every day. So your page.html can include a file called all-my-js-v4.js which has a long cache life (like, a year). If you update your JavaScript, create a new all-in-one file called all-my-js-v5.js and update page.html to include that instead. The next time the user sees page.html, they'll request the updated file; but until then, they can use their cached copy.
If you really want to do this on-the-fly, if you're using apache, you could use mod_pagespeed.
If you're using .NET, I can recommend Combres. It does combination and minification of JavaScript and CSS files.
I know this is an old question, but you may be interested in this project: https://github.com/OpenNTF/JavascriptAggregator
Assuming you use AMD modules for your javascript, this project will create highly cacheable layers on demand. It has other features you may be interested in as well.
Question
If you use a single javascript file to hold all scripts, where do you put scripts that are for just one page?
Background
This may be a matter of opinion or "best practice" but I'm interested in others' opinions:
I'm using the html5 Boilerplate on a project. They recommend you place all javascript in a single file script.js for speed and consistency. Seems reasonable.
However, I have a bit of geolocation script that's only relevant to a single page, and not others. Should I break convention and just put this script on the page below my calls to the javascript libraries it depends on? Just put calls to the relevant functions (located in the script.js) file, below the links to the libraries they depend on?
Thanks!
The good folks at html5 boilerplate recommend putting all of your javascript in script.js so that the browser will only have to load that one file (along with the others that h5bp uses) and to allow caching of that file.
The idea is not to get caught up in the "recommended" way, and to think about things related to your own applications.
This geolocation file is only going to be used on this one page, right? It will never be used anywhere else.
The script.js file will be used on multiple pages.
Well, then it wouldn't make sense to put a "whole script" that will only be needed on one page in the script.js file. You should make the file external and call it separately on the page that it is needed. This will keep you from bloating the script.js file for functionality that may never get used by that user.
However, if your "whole script" for the geolocation functionality is pretty small, then include it in script.js. If it doesn't add to the speed of the download for that file, then it makes sense to include it there.
The gist of all of this is, What is the best trade off for my application?
These things we know to be true:
cached js files are good
fewer files to download are good
smaller files to download are good
maintenance is important
Once you think of these things in terms of your application, the decision making becomes a bit easier. And remember, decisions that trade off milliseconds are not going to make much of a difference in your user's "perception" of how fast your page is.
The browser will only download the .js files once (unless something is happening to discourage the browser from caching). So if you expect all of your users to hit the one page that uses geolocation sometime during their session, then you might as well give it to them early. If you expect maybe a tiny percent of your users to eventually hit the geolocation page, then maybe you might want to split them.
Split it out into a separate .js file so that it can be cached. Then reference both external .js files from your page.
I think you should put it in a separate file. Putting all the scripts in one single file could cause unexpected behavior and conflicts. I like to have one script file for the javascript that all pages will use containing plugins, helper functions, formatting functions etc. And then create one separate js file for everything that is relevant just for each page.
If you still want to have just one js file in the browser you could take advantage of one of those utilities that combine multiple js files into one.
My understanding was that only the javascript code placed inline in the HTML page would show, never the code stored in .js files
...and I had never seen in any browser code in a .js file show on the clientside...
until I started to use Chrome and noticed all my code is available for viewing???
Have I been convincing myself the code is safe in .js files, when in fact it never was?
and while on this subject can a responder be totally clear whether the code in .js files can be hidden or not.
I have read many posts that left me doubting whether it can be done or not.
. Some say to place it in a .js file on the server so it executes on the server...
--- using 'language=javascript' and an html line with 'runat server'? no idea how to do that.
--- But, would that not defeat the purpose of speed, and refresh since the server has to be accessed?
--- might as well code it in the code-behind???(C#, VB, php, ...)
. Some say use an AJAX call etc... but it seems others contradict that, saying the code lands on the clientside anyway thus will show? ...and I am assuming this would be a callback with no page redraw...
JavaScript is executed in the browser, this means the script has to be submitted to the client. So, of course anyone can view the code, wether it's happening in the developer tools, getting the direct link out of your html or, for example, using a http sniffer.
Altough, there are some methods to make the script unreadable for humans.
Minifying your script is a good practice in general. It decreases file-size, so the client has to download less, speeding up loading time. After all, this does not really help making your script "unreadable" for users, there are a lot of deminifying services all around the web.
Still, there is another way: obscurifying (or obfuscate) your script. This replaces the code to make it unreadable. Unfortunately, I don't really have experience with using this technique, so I don't know how it would affect the performance of the js-code.
Maybe you want to have a look at this: How can I obfuscate (protect) JavaScript?
Javascript code can be seen even if its in a .js file the only thing you can do to make it little tough to understand is minify the js file.
Actually, javascript code stored in a separated file wont be shown directly; the user must explicitly type the name of the file in the address bar to see its content.
The only way to hide it is, as said before, to minify the file, which compress the file and make it unreadable for humans.
I have a couple of questions that are somewhat related so I'm posting them all on a single question on SO...
Question 1:
I'm currently doing this Facebook application where I'm using jQuery UI Tabs, there's only 4 where 2 of them are loaded through Ajax. The main page is index.html, this is where the tabs code is placed and for the 2 tabs loaded through Ajax, I have two different files, tab1.html and tab2.html.
Currently, the jQuery tabs initialization and Facebook JavaScript initialization is done on index.html. Both tab1.html and tab2.html have JavaScript code that belongs to those pages. For instance, tab2.html has a form and there's some JS (with jQuery) code to validate the form, this code is irrelevant to tab1.html as the JS code on tab1.html is irrelevant to tab2.html.
My question is, should I keep doing this or maybe aggregate all the JS/jQuery code in index.html, tab1.html and tab2.html in a single global.js file and then include it in index.html?
I though of doing this but there will be irrelevant code loaded if the user never opens tab1 or tab2. The benefit of using a single global.js file is that I could pack/minify the file, which I couldn't do if I included each code block in each respective tabX.html file.
Question 2:
As I'm using jQuery, I'm also using lots of plugins (actually only 3 for now, but that number can grow). Some of them provide a minified JS and I use those when available, when they are not, I use the normal versions of course.
There's also the requests problem. If I have lots of plugins, say 10, it will be 10 requests for those plugins. And there is also the fact that some plugins are used in tab1.html but not on tab2.html and vice-verse.
How should I load all the plugins in a minified/packed version on a single web request? Should I do that manually before publishing my app (packing and merging them into a single file) or could I use the PHP version of Dean Edwards's Packer and pack/merge all plugins on the fly? Would this be a good approach?
Question 3:
If the answer on Q1 was something like "merge all code in a single global.js file", should I include the global.js file in the packing/merging script I described above on Q2?
Doing this would simplify everything. I could have my development environment properly organized with all .js files, for the plugins and the global.js in the appropriate folders without bothering with anything else. The packing/merging should take care of the rest (pull the files from the respective folders, send the respective JS headers and output one single packed .js file).
The one thing that's confusing me the most is that not all plugins are used for every tab, not all code is for every tab too. Still, a chunk of the code is global to every tab and the index. This also simplifies everything as: a) I don't have to worry to add the needed code to each tabX.html file and can I simply look at them as HTML templates and nothing else; b) I don't have to be bothered in including the necessary plugins where I need them as I'm currently using $.getScript() from jQuery to load the plugins I need when and only when I need them, but I'm not sure this is a good approach and the code feels dirty and ugly like this.
Question 1:
Pack them all into a single .js file. This will make maintenance easier, and the tiny bit of overhead for the user loading a little js they they potentially may not use does not matter. I would also let Google load the jQuery library for you and then have all of your js code in a single separate file.
Question 2:
As these plugins don't really change I would manually combine them. Closure Compiler is good at this. When minifying use the highest setting that does not give any warnings.
Question 3:
Yes you will want to minify the global.js
When the browser downloads the global.js it's cached for an amount of time. Thus when you call the entire global.js again on a different page, its not re-downloaded it looks at your local copy first. So you do a little bit more work at first on the initial download, but from then on, it should be quicker.
Generally best practices related to javascript for speeding up website loads are:
Minify all javascript and put all of it into a single file (make as much of your javascript external as possible).
Put javascript at the bottom of the document.
Force web server to assign expiration date in the future and use a timestamped query string to invalidate old versions of javascript files, this will prevent unnecessary requests for your javascript if it has not changed. (ie: in httpd.conf ExpiresByType application/x-javascript "access plus 1 year", in your document: <script type="text/javascript" src="/allmy.js?v=1285877202"></script>)
Configure your web server to gzip all text files.
The main reason why you should keep too much javascript away from tab pages is because it will kill user experience. When a user clicks on a tab for the first time it will grab all the components needed on the fly which makes it kinda sluggish.
You're question is only semi-specific as we don't know a lot of things about your site like exact file sizes, how the modules are really used.
The general idea would be to find balance between modularity and speed.
When you're combining modules together these are the general ideas you should consider:
how often does this module change?
how often is this module used?
how big is this module (filesize)?
Then put the most used, stable codebase and merge it into one. Then you should include the rest site specific functionality on the tab pages.
Also, make sure to load javascript asynchronously as it won't block rendering of the page (and tabs).
Another combined answer:
if adding all the JS together in packed/minifed version generates no more than 30k of file size you're better off combining it. A single extra connection for a file (assuming it's not cached) is worth 10-20k of extra JS download. This has to do with browsers opening and closing connections vs streaming extra 20k on an established connection. The threshold also depends on your user distribution. If you have a lot of dial-up or low bandwidth users your threshold will be smaller.
I typically recommend combining and loading as 1 file unless the library is very obscure and requires a very edge case for it to be triggered on a page. Ex: Hover triggers functionality Y but it's on a feedback widget that gets less than 1% of traffic- don't bother combining.
Minifying and Packing is a little overrated these days. With the vast majority of browsers supporting gZip the amount of data consolidation gZip provides of the file over the wire during browser transmission has virtually the same effect as min/pack. However, there is a small cost on the browser to unpack it. Having said that, it's still good practice to min/pack the code since not all browsers support it, you may not want the file to be gZip enabled, etc.
I've used online packers against 3rd party module and it works fairly well. However, there are times when it can cause an issue so make sure to test your manually packed version before deploying.
Alternate:
If you feel that your users will rest on your index page for longer than 10 seconds you could pre-load the additional libraries separately using Js Loader Prototype pattern.
Steve Souder's Even Faster Websites is a book you should look into.
Firstly one experience slowdowns because whenever an external script is linked the browser waits for the script to download, parse and then execute. After this only it regains processing rest of the request. So to avoid such slow downs one can look at parallely downloading the scripts. Few techniques are Ajax the scripts if the scripts are in the same domain or use Script Dom element or Script in iframe if the scripts are on external domains
Q1 : For me modularising all the content is a better option with respect to further development if the page content has to be changed constantly. Responsiveness is very important for the end user. A small global.js will help in getting the app up and running.Parallely one can download the tabX.html.
Q2: As the jquery plugins rarely change. The plugins for the tabX.html pages can be downloaded parallely and locally cached so when the tabX.html is loaded the required plugins need not be fetched. SO all the plugins required by the main page should be in one single file and the ones used by the tabX.html's should be in different files.
Q3 : its a personal choice here. Do you want it to be developer friendly or user friendly. I bank on user friendliness. Making responsive and efficient apps is our job !!!. All the advantages of packing everything into a singe files is you will have ease in development. Well ugly code begets beautiful apps :). Users are speed-aholics. For eg. when google changed its 10 results per page to 20 they saw a considerable drop in search queries. So my opinion is not to pack all of them into one and load each parallely
some of the techniques and relevant links on testing each:
XHR eval /ajax : http://stevesouders.com/cuzillion/?ex=10009
XHR Injection : http://stevesouders.com/cuzillion/?ex=10015
Script in Iframe : http://stevesouders.com/cuzillion/?ex=10012
Script DOM element : http://stevesouders.com/cuzillion/?ex=10010
Question 1:
The best practice would be to place all js files in a single "global" file. This minimizes your HTTP Requests. Let's say you have 5 plug-ins, this would me you need to do 5 request, wherein if you combine them as one, you only need to request it once. This might be a little bit heavy on the first load, but the next time around this file will be cached by the browser, so..no worries about the size. HOWEVER, be careful about the sequence of the scripts when combining it. (I.E. : JQuery script should be placed first on the js file before JQuery UI's)
http://articles.sitepoint.com/article/web-site-optimization-steps/4
http://code.google.com/speed/page-speed/docs/rtt.html
Question 2:
You can do it manually or automatically.Dean Edward's Packer is a good choice. If you're using ASP.NET, you can check MB Compression Handler, if you're using APACHE with PHP perhaps you can change the configuration of your htaccess to gzip it
Question 3:
It'd be better if you pack the "global" javascript file as well. This could save up bandwidth and save more time to load. You got the point, combining all the js files you need for the site will save you time from including individual scripts.
I've been doing a little JavaScript (well, more like jQuery) for a while now and one thing I've always been confused about is where I should put my scripts, in the <head> tag or in the <body> tag.
If anyone could clarify this issue, that'd be great. An example of what should go where would be perfect.
Best practices from google and yahoo say that, for performance, javascript should always be put in an external file, and linked to your page with a <script> tag located at the bottom of the html, just before the closing of the <body> element.
This allows the browser to render the entire page right away, instead of stopping to evaluate javascript.
You mentioned three places:
In tags;
In the HTML; and
In an external file.
Let me address each of those.
Best practice is to have common Javascript in one or more external files and the less files the better since each JS file loaded will block loading of the page until that JS file is loaded.
The word "common" is extremely important. What that means is you don't want to put page-specific Javascript code in that external file for caching reasons. Let's say you have a site with 1000 pages. Each page has JS code specific to it. That could either be 1000 different files or one really big file that executes a lot of unnecessary code (eg looking for IDs that aren't on that particular page but are on one of the 999 others). Neither of these outcomes is good.
The first gives you little caching boost. The second can have horrific page load times.
So what you do is put all common functions in one JS file where that JS file only contains functions. In each HTML page you call the JS functions needed for that page.
Ideally your JS files are cached effectively too. Best practice is to use a far futures HTTP Expires header and a version number so the JS file is only loaded once by each browser no matter how many pages they visit. When you change the file you change the version number and it forces a reload. Using mtime (last modified time of the JS file) is a common scheme, giving URLs like:
<script type="text/javascript" src="/js/script.js?1233454455"></script>
where that mtime is automatically generated. Your Web server is configured to serve JS files with an appropriate Expires header.
So that mixes external files and in-page scripts in (imho) the best way possible.
The last place you mentioned was in the tag. Here it depends somewhat on what JS libraries and frameworks you use. I'm a huge fan of jQuery, which encourages unobtrusive Javascript. That means you (hopefully) don't put any Javascript in your markup at all. So instead of:
do stuff
you do:
do stuff
with Javascript:
$(function() {
$("#dostuff").click(doStuff);
});