As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
How do you guys organise your javascript code? I know that it is good practice to store the code in an external .js file and this is fine for code that is run in multiple pages but how do you organise if you have, say 20 pages, and only 1 of them uses a particular function. Do you create a new external file for that 1 page or create the code inline?
I do two things:
I put all my site's Javascript in one or more files;
I include that file or files on every page that uses any Javascript;
Those files are cached effectively such that they are only ever downloaded once (until they change); and
Pages call the functions they need from those external files.
If your site is one page then put it inline.
If your site is 20 pages and they all use a little bit of Javascript, put it all in one files, include it on every page and call the functions with inlien Javascript as necessary in each file.
I write about this and more in Supercharging Javascript in PHP. Sure it's PHP-specific but the principles are universal.
Basically every extra HTTP request is a problem. So if you have 20 pages each with a different Javascript file then that's a problem, even if those files are small. It's better to combine all that Javascript in one file, download it just once (with effective caching) and just use what you need.
To give you an example. External JS file contains:
function delete_user(evt) { ...}
function suspend_user(evt) { ... }
function unsuspend_user(evt) { ... }
One of your Web pages contains:
$(function() {
$("#delete").click(delete_user);
$("#suspend").click(suspend_user);
$("#unsuspend").click(unsuspend_user);
});
This way you get an external JS that contains all your site's Javascript but none of it is actually used. Use comes from inline code in the pages. This way there is no overhead of having the larger JS file.
Whatever you do, don't put in ALL initialization in your Javascript file. I once made this mistake and put a huge $(function() { ... } function into the external file on the grounds that if the relevant IDs weren't in the page, nothing would happen. There ended up being enough of this code to add nearly half a second to the page load time (and the site wasn't that big).
The browser shouldn't redownload the javascript file once it has it, so I would put it into the single Javascript file. That saves another connection/request to the webserver, and it keeps the code in one place rather than having script tags and code in your HTML/JSP/PHP/etc files. I.e., it's more maintainable, and it's very little overhead to get the code (unless it's a 1000 line monster! but that's another problem entirely) even if it isn't used.
Not that I don't have script blocks in some files, for very very specialised cases. In the end it comes down to what you are happy with - but consistency across the project is what is most important, so don't have a one off script in one place, and then do something different elsewhere.
ALWAYS put JavaScript in a file external to HTML. The problem with JavaScript that exists in page is that it typically exists in the global namespace, which could easily cause namespace collisions that makes code crash.
So, always put JavaScript in an external file.
With that said you should organize your code in an object-oriented manner. Try to capture an entire application representing a single point of execution to a single named function. Always write your code using a single var command per function, which should go at the top of the function, so that your code is easier to read. Ensure all variables and functions are declared with a var command or they will into the global namespace, which is potential failure. Put sections of execution of a giant function into smaller child functions, because this makes code easier to maintain when you can point to a particular named block when debugging or writing enhancements.
Also, always run your code through JSLint to verify syntax accuracy.
If you only have a small amount of code I don't believe it is worth the effort to split it up.
Depending on how much JS you have, consider a build process that can concatenate your separate JavaScript files into one, minified single download.
YUI is incredibly modular. They have a 'core' set of includes and then you can supplement these with the widgets you actually use. For instance, I have no interest in using their file uploader widget so never include the JS for it.
Cache the JS for a date far in the future. If you need to make a change, append a version stamp to the end of the SRC attribute, i.e. my-code.js?v=91
Use namespaces to avoid polluting the global scope. Again, YUI is very organised in this regard - see the YAHOO.namespace() function.
I would say put it in an external file. Chances are you will need to add new functions to it anyway, but also, from an SEO point of view, keeping it in an external file is preferable.
For only one function it would be better to code inline.
I won't include a 100KB Util script file for just calling a Trim function inside it.
If the file is already cached then it won't be a problem if you refer this in a page which calls only one function inside the file.
If I have a choice, I put the JS functions in external files, but not all in one file. Cache or no cache, I group files by their functionality and organize them similar to Java packages. If I have an utility function, say something generic like trim(), that goes to the top most JS file and all pages can use it. If I have something specific to a part of the site (unused in other parts) that goes in something like a sub-package, just for that specific part… and so on.
Of course you must use common sense so you don’t overdo it, and have let’s say a function per JS file. If you have fine grained JS files, that will affect you when your site evolves and you find yourself moving functions from sub-packages to an upper package or the other way around. I think one parent utility JS and one JS per site functionality should, most of the times, suffice.
Related
I have seen a lot of websites with some function (p,a,c,k,e,d) in their JavaScript code. The different websites may have different bodies of this function, but they all use the same parameter names (p,a,c,k,e,d). Is it a standard or a library or something?
Secondly, it seems that this function is supposed to be executed as soon as the page loads. Like the following snippet from a website.
Can you help me in understanding this code? eval() is used to evaluate expressions like 2+3 but how is the following code passing a function to it?
try{
eval(
function(p,a,c,k,e,d)
{
//some code goes here
}
}catch(err){}
So if you use http://matthewfl.com/unPacker.html as I posted in the comments, it "unpacks" the code into this:
(function()
{
var b="some sample packed code";
function something(a)
{
alert(a)
}
something(b)
}
)();
It doesn't seem to be malicious. For a soft argument on why you would use this, see javascript packer versus minifier:
Packed is smaller but is slower.
And even harder to debug.
Most of the well known frameworks and plugins are only minified.
Packer does more then just rename vars and arguments, it actually maps
the source code using Base62 which then must be rebuilt on the client
side via eval() in order to be usable.
Side stepping the eval() is evil issues here, this can also create a
large amount of overhead on the client during page load when you start
packing larger JS libraries, like jQuery. This why only doing minify
on your production JS is recommend, since if you have enough code to
need to do packing or minify, you have enough code to make eval()
choke the client during page load.
Minifier only removes unnecessary things like white space characters
where as a Packer goes one step further and does whatever it can do to
minimize the size of javascript. For example it renames variables to
smaller names.
It's a function which decompresses compressed/obfuscated javascript code. Many JS libraries and scripts make use of it.
There are online tools where you can pack and unpack code via the browser, which use the function.
As I have seen that eval(function(p,a,c,k,e,d){}) is used in http://www.indiabix.com which uses it for hiding whole contents when user get download the page and open it . Maybe that is the inner workings of the particular code.
I am building a front-end UI framework for developers in my firm to use to build internal web apps. It consists of customized Bootstrap, jQuery, other open-source libraries, internal modules and stylesheets. The user environment is entirely IE9 and my server is .NET 3.5. I am hosting the shared files. Dev teams in the firm will place the links in their project pages and apply the framework to their pages.
I want to offer them the simplest method of implementing this which would be one line of code to paste that builds the library for them. Cutting and pasting 30 lines of code is stale the moment Ctrl + V is pressed, it leaves me no control and is simply inelegant.
Failed Experiments
I tried using Head.js and LazyLoad both of which use best practices for inserting scripts. But each of them has caused either content to display before styled or conditions where methods are called before scripts load. I am giving up on this approach.
It's too volatile.
A simple document.write() solution
Over the weekend, I thought: Why don't I just make a js file named "framework,js", add the script and link files in order with a stack of document.write() lines. Tell developers to put it in the head and that's it. Heck I could add the necessary metatags for IE9 and mobile too for that matter. It's so nasty and simple... but it just might work!
The user base is on an internal network and of limited size. Bandwidth is not a problem. I'll test performance before I choose this. I can direct the developer teams on where to place the link.
Knowing this and providing it actually works, is there any reason why I shouldn't do this?
My only other option to explore is bundling on the server. I am hoping not to have to resort to this since I don't own the server myself and I am not a .NET developer.
Your proposed approach is an excellent one for your situation. It has several advantages over the more sophisticated solutions, including utter simplicity, completely predictable order of execution, and full compatibility with scripts that may not lend themselves to asynchronous loading. I have used it many times in production applications, as have many other developers.
Of course the other solutions have their advantages too, but for what you're doing there is nothing wrong with good old document.write().
It sounds like you have a number of scripts and stylesheets and are probably loading them from a common directory (or a common root directory). To reduce repetition in your framework.js file, you might want to define two functions, one to write a <link> tag for CSS and another to write a <script> tag for JavaScript. So a skeleton framework.js file might look something like this:
(function() {
var scriptBase = 'js/';
var styleBase = 'css/';
function writeStyle( name ) {
document.write(
'<link rel="stylesheet" href="', styleBase, name, '">',
'</link>'
);
}
function writeScript( name ) {
document.write(
'<script src="', scriptBase, name, '">',
'</script>'
);
}
writeStyle( 'one.css' );
writeStyle( 'two.css' );
writeScript( 'one.js' );
writeScript( 'two.js' );
})();
Note that you don't have to do any special escaping of the </script> text as you may see in code that uses document.write(). That's only necessary when you're putting this code directly inside a <script> tag within the HTML file. The purpose of that escaping is to prevent the enclosing <script> tag from being closed by the </script> text inside the document.write() call. Since your code is in an external .js file this is not an issue: the presence of the </script> text inside this file won't terminate the .js file.
Another point to keep in mind is that all of the document.write() calls you make inside a .js file are inserted into the document after the .js file that writes them. So don't expect to be able to do a document.write() inside framework.js and then have other code inside framework.js that depends on the .js file you just wrote. All of those .js files (and .css) are loaded after framework.js, not interleaved with it.
One more consideration, of course, is load time. Your page could load faster if you combine and minify your CSS and JS files. But if these are internal web apps, page load time may be the least of your worries: reliability and maintainability may be more important. And in any case you can always use the document.write() solution to get up and running right now, and later optimize this only in the unlikely event that you need to.
I have several javascript (coffee script) files in my Rails javascripts directory. The code is logically divided into different files. However, each file starts with $(document).ready -> and some files share common helper functions.
What is the best way to factor out the helper functions? Should I just put them all in some other file that gets included earlier in application.js?
Also, is it normal to have the code divided up the way mine is, where every page does $(document).ready ->? Doesn't this mean that all of my code is called on every page, regardless of whether or not it is relevant? Are there alternatives to this organization?
I'm not sure if this question is specific to Rails or relevant to javascript and jQuery in general.
I do think this is a Rails question, and a good one.
The normal paradigm in Rails, where "global" stuff goes in application.* is a little messed up with the asset pipeline, since the application.js really acts as a manifest, rather than a common file. Of course you could add stuff there, or even create an application.js.coffee for your common code. I decided to create a file called common.js.coffee (and in another case shared.js.coffee), which in my case was automatically handled by the require_tree . directive.
(Update based on comment from #jonathan-tran) In some cases, you may just want methods called on document ready for all pages -- for example, I used this to make a datepicker available to any field in any view. If, instead you want methods (actually global functions) available to be callable, you'll need to export the coffeescript functions to variables, for example by attaching to the window object. You can do both in a shared file.
It is true that if you use generators you'll end up with files for every controller which, if there's no specialized code result in a series of redundant $(document).ready -> statements when assets are compiled. So just get rid of the ones you don't use. But following the pattern of separating functionality specific to a page makes good sense to me and works well -- I know where to look to find stuff and that's worth a lot as a project grows.
And another rule I have learned with Rails: go with the flow. If that's how Rails does it, it's probably a good way. They do indeed think about these things. Don't fix what works :-)
Scenario:
A web site with x number of pages is being served with a single, concatenated JavaScript file. Some of the individual JavaScript files pertain to a page, others to plugins/extensions etc.
When a page is served, the entire set of JavaScript is executed (as execution is performed when loaded). Unfortunately, only a sub-section of the JavaScript pertains directly to the page. The rest is relevant to other pages on the site, and may have potential side-effects on the current page if written poorly.
Question:
What is the best strategy to only execute JavaScript that relates directly to the page, while maintaining a single concatenated file?
Current solution that doesn't feel right:
JavaScript related to a specific page is wrapped in a "namespaced" init function for that page. Each page is rendered with an inline script calling the init function for that page. It works hunky-dory, but I would rather not have any inline scripts.
Does anyone have any clever suggestions? Should I just use an inline script and be done with it? I'm surprised this isn't more of an issue for most developers out there.
Just use an inline script. If it's one or two lines to initialize the JavaScript you need that's fine. It's actually a good design practice because then it allows re-use of your JavaScript across multiple pages.
The advantages of a single (or at least few) concatenated js files are clear (less connections in the page mean lower loading time, you can minify it all at once, ...).
We use such a solution, but: we allow different pages to get different set of concatenated files - though I'm sure there exists different patterns.
In our case we have split javascript files in a few groups by functionality; each page can specify which ones they need. The framework will then deliver the concatenated file with consistent naming and versioning, so that caching works very well on the browser level.
We use django and a home-baked solution - but that's just because we started already a few years ago, when only django-compress was available, and django compress isn't available any more. The django-pipeline successor seems good, but you can find alternatives on djangopackages/asset-managers.
On different frameworks of course you'll find some equivalent packages. Without a framework, this solution is probably unachievable ;-)
By the way, using these patterns you can also compress your js files (statically, or even dynamically if you have a good caching policy)
I don't think your solution is that bad although it is a good thing that you distrust inline scripts. But you have to find out on what page you are somehow so calling the appropriate init function on each page makes sense. You can also call the init function based on some other factors:
The page URL
The page title
A class set in the document body
A parameter appended to your script URL and parsed by the global document ready function.
I simply call a bunch of init functions when the document is ready. Each checks to see if it's needed on the page, if not, simply RETURN.
You could do something as simple as:
var locationPath = window.location.pathname;
var locationPage = locationPath.substring(locationPath.lastIndexOf('/') + 1);
switch(locationPage) {
case 'index.html':
// do stuff
break;
case 'contact.html':
// do stuff
break;
}
I'm really confused exactly why it doesn't feel right to call javascript from the page? There is a connection between the page and the javascript, and making that explicit should make your code easier to understand, debug, and more organized. I'm sure you could try and use some auto wiring convention but I don't think it really would help you solve the problem. Just call the name spaced function from your page and be done with it..
In todays modern age, where lots of (popular) javascripts files are loaded externally and locally, does the order in which the javascripts files are called matter especially when all local files are all combined (minified) into one file?
Furthermore, many claim that Javascript should go in the bottom of the page while others say javascript is best left in the head. Which should one do when? Thanks!
google cdn latest jquery js | external
another cdn loaded javascript js | external
TabScript ...js \
GalleryLightbox ...js \
JavascriptMenu ...js \
HTMlFormsBeautifier ...js > all minified and combined into one .js file!
TextFieldResize ...js /
SWFObjects ...js /
Tooltips ...js /
CallFunctions ...js /
Order matters in possibly one or more of the following situations:
When one of your scripts contains dependencies on another script.
If the script is in the BODY and not the HEAD.. UPDATE: HEAD vs BODY doesn't seem to make a difference. Order matters. Period.
When you are running code in the global namespace that requires a dependency on another script.
The best way to avoid these problems is to make sure that code in the global namespace is inside of a $(document).ready() wrapper. Code in the global namespace must be loaded in the order such that executed code must first be defined.
Checking the JavaScript error console in Firebug or Chrome Debugger can possibly tell you what is breaking in the script and let you know what needs to be modified for your new setup.
Order generally doesn't matter if functions are invoked based on events, such as pageload, clicks, nodes inserted or removed, etc. But if function calls are made outside of the events in the global namespace, that is when problems will arise. Consider this code:
JS file: mySourceContainingEvilFunctionDef.js
function evilGlobalFunctionCall() {
alert("I will cause problems because the HTML page is trying to call " +
"me before it knows I exist... It doesn't know I exist, sniff :( ");
}
HTML:
<script>
evilGlobalFunctionCall(); // JS Error - syntax error
</script>
<!-- Takes time to load -->
<script type="text/javascript" src="mySourceContainingEvilFunctionDef.js"></script>
...
In any case, the above tips will help prevent these types of issues.
As a side note, you may want to consider that there are certain speed advantages to utilizing the asynchronous nature of the browser to pull down resources. Web browsers can have up to 4 asynchronous connections open at a time, meaning that it's quite possible that your one massive script might take longer to load than that same script split up into chunks! There is also Yahoo Research that shows combining scripts produces the faster result, so results vary from one situation to another.
Since it's a balance between the time taken to open and close several HTTP connections vs the time lost in limiting yourself to a single connection instead of multiple asynchronous connections, you may need to do some testing on your end to verify what works best in your situation. It may be that the time taken to open all of the connections is offset by the fact that the browser can download all the scripts asynchronously and exceed the delays in opening/closing connections.
With that said, in most cases, combining the script will likely result in the fastest speed gains and is considered a best practice.
Yes, depending very much on what you do.
For example, if a.js had...
var a = function() {
alert('a');
}
...and b.js had...
a()
...then you wouldn't want to include b.js before a.js, or a() won't be available.
This only applies to function expressions; declarations are hoisted to the top of their scope.
As for whether you should combine jQuery, I reckon it would be better to use the Google hosted copy - adding it to your combined file will make it larger when there is a great chance the file is already cached for the client.
Read this post from the webkit team for some valuable information about how browsers load and execute script files.
Normally when the parser encounters an
external script, parsing is paused, a
request is issued to download the
script, and parsing is resumed only
after the script has fully downloaded
and executed.
So normally (without those async or defer attributes), scripts get excuted in the order in which they are specified in the source code. But if the script tags are in the <head>, the browser will first wait for all scripts to load before it starts executing anything.
This means that it makes no difference if the script is splitted into multiple files or not.
If I'm understanding your question I think you're asking if it matters where in a file a function/method is defined, and the answer is no, you can define them anywhere in a single source file. The JavaScript parser will read in all symbols before trying to run the code.
If you have two files that define variables or functions with the same name, the order that they're included will change which one actually is defined