jquery structure - one function per file - javascript

I am primarily a c# programmer. I have recently been getting into some jquery development. when I am working on applications in c#, I create a new class file (.cs) for every new class that I create.
How do people generally structure their jquery/javascript applications. I would like to reuse some functionality across pages, so do I put each function in it's own .js file? or is it best practice to group like functions into files? I can't see putting each on in it's own file as that would create many calls to import individual file into a page....
How are other people handling these types of situations.
Thanks for any thoughts.
EDIT - I should have mentioned that I am beginning to look at unit testing with QUnit and figured it would be good to have proper structure of my project to better facilitate unit testing.

If you DO put them all in separate files, you would want to have a build script that combines and minimizes them into a single one (or just a few) so you do not have 500 Javascript files to download to your browser.

I would suggest putting your common functionalities to a util.js file and then arrange your javascript codes according to functionality.
However it is not a good practice to have lots of js files included in every page, thus you might consider combinin the files into a single file and minifying that final js file. this way you would have optimized your final product while being able to unit test functionalities separately.

I generally keep all plugins into their perspective files but functions I create I tend to place into a "global.js" file that the entire site will pull from. Then I don't have to worry about pulling in specific files when a need a specific function. It will all be in the global.

Put it all in one file. Multiple HTTP requests are more expensive than big files, plus you're assured that the file containing the function you need is already loaded.

Related

Is It Possible to Dynamically Generate JavaScript Reference Directives?

I'm working on a team of developers that keeps reference directives in various files for intellisense purposes. As you can imagine, it's impossible to maintain these files. As such, I'd like to know if there's a way to dynamically generate them. Any way. At all. No matter how kooky.
Here's a reference to the kind of thing I'm talking about: http://msdn.microsoft.com/en-us/library/vstudio/bb385682.aspx#ReferenceDirectives
I'm trying to do this on the fly. Say, to dynamically make some references for every js file in a folder. Whatever. Anything. I'll run with it once I get a good starting point.
Why not use T4 to read all the files in the current folder and below? (accounting for, if necessary scripts that are not actually included in the project but present in the file system).
Or even better and more likely related to what you are trying to do?
Use the nice centralized _references.js VS helper for scripts that are core in functionality to the others that you are editing.

Can you use multiple .JS files when developing a complex Javascript application?

Coming from a C# background where every class is (best practices) stored in its own individual file, it makes development quite clean. I've never written anything complex in Javascript in the past, but I am starting to learn HTML 5 and I want to write a complex game using the HTML 5 canvas.
Putting all of my functions and code into a single .js file seems very messy. Is there a way to split it up, or a tool/IDE that lets you develop using separate files and compile them into a single one for deployment?
I guess I am looking for some best practice advice. Questions like this generally seem to get closed, so here are my specific questions to adhere to the SO FAQ that demands practical, answerable questions:
Does complex JS development usually involve all the code being in a single JS file? Eg. you're writing space invaders, do you just have spaceinvaders.js or do you have ships.js, logic.js etc.
Is it possible to split up your JS (whether using multiple script tags or pre-compiling to a single JS file) or to just put it all in a single file?
What's the industry standard? Does the HTML 5 spec make any recommendations?
There two possible ways.
Personally, I would use a build tool to simplify working with multiple files.
Using a build tool
Grunt
My favourite tool to keep up with complex js applications is grunt. With grunt you can develop in as many files as you want and use its plugins watch and concat to automatically concat them on save. You can do a lot more but this is the basic use case which may be helpful for you.
Grunt requires nodejs and takes some time to setup. But once you are ready with your Gruntfile setup it really speeds up your development process.
To make your project ready for production use you can also minify your scripts with some configuration and a single command.
A lot of the major javascript libraries are using grunt, easily recognizable based on their Gruntfile: jQuery, AngularJS, Twitter Bootstrap etc.
Grunt is also part of the development toolset yeoman.
Brunch
Brunch is another build tool which allows you to do similar things like grunt does.
Loading only the needed files
If you are developing a huge single page application and are concerned about the startup time of your application, one single file may not be the best solution. In this case you can use a javascript module loader.
Require.js
Therefor require.js is a goot fit. It allows you to only load the actual needed files on the current page. Though setting up require.js is a bit more work than setting up grunt.
Of course you can use more than one javascript file. How else would libraries like jQuery or Knockout function?
One thing to keep in mind, though, is that one of the things you want to do to keep your pages feeling snappy is to reduce the total number of http requests per page load. Adding a bunch of javascript files that are loaded separately causes an additonal request for each extra file. Therefore, you might want to experiment with a system for your build that stitches your javascript files together into a single item that you can use at deployment. There are a number of solutions out there that will do this for you in an automated way.
you could consider using requirejs - a very nice libray to split your javascript to modules.
it also provide a tool that you can "combine" all modules to a single file.
You can use as many javascript files as you want. Just add a link to them in your html code:
<body style="background-color: black" onload="main();" >
<!-- Your HTML body contents -->
<!-- Your scripts (here, I used HTML5 BoilerPlate to setup, and the links to jquery are provided) -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script src="js/main.js"></script>
</body>
Then you can hookup your main.js to listen for the main() function call:
function main() {
//here you can do your basic setup or delegate the control of the app to a different .js file.
}
or the jQuery document ready callback:
$(document).ready(function() {
//here is a good spot to hookup other jQuery listeners
});

Calling javascript

I am setting up a site that relies on a lot of javascript items and i want to try and set it up so the pages only call what they need.
there are different types of functionality so i am goig to break them into their own js files to make it easy to use.
For example if there is a drag and drop functionality then i will include the js file for drag and drop. within that will be a generic call using a class to turn on the functionality. This way it is only used on a page that uses drag and drop.
This gets more compacted when i have ajax calls some are on change events on a select for example while others are on a button.
I could separate these into different files for each type perhaps.
my concern is if a call needs more parameters to be passed or a different url then where does this code go to make the call?
I don't really want to have code within the page itself if i can help it.
I would love to hear your thoughts on how to best set this up
RequireJS might be your answer:
RequireJS is a JavaScript file and module loader. It is optimized for
in-browser use, but it can be used in other JavaScript environments,
like Rhino and Node. Using a modular script loader like RequireJS will
improve the speed and quality of your code.
This sounds similar to what I'm doing, so here what I've done:
One central file that contains functions that are used pretty much everywhere.
A folder containing files that are used in several places, but aren't worth including everywhere.
A folder containing files that are only used on one page.
Then, simply include the necessary <script> tags and go!
Hmm, have you looked at existing frameworks http://speckyboy.com/2010/05/17/15-javascript-web-ui-libraries-frameworks-and-libraries/?

packaging multiple javascript files

I am developing a javascript library made up of a few tightly coupled classes. The classes are broken up into individual .js files, but for brevity's sake, I envision the end user including a single .js file encompassing the entire implementation.
My question is, what is the ideal method for distributing the API? Should I simply repackage all the code into a single .js file, should I keep the existing file structure and setup a series of
document.write('<script src="file1.js"><\/script>');
commands into a 'primary' script file, or is there another way that makes more sense?
Thanks!
I think if you don't intend for the user to jump in there and need to modify it and it's tightly coupled like you mentioned you should put it all in a single JS file and then minify it.
You can provide an unminified version as well but seems for their simplicity you should put it all in a single JS file.
For performance and maintenance reasons, I believe it's better to package them into a single file. The fewer http requests made to retrieve scripts, the better performance (in general - very long scripts can also cause performance slowdown.) I'd also recommend namespacing your api.

How do you manage your Javascript files?

Nowadays, we have tons of Javascript libraries per page in addition to the Javascript files we write ourselves. How do you manage them all? How do you minify them in an organized way?
Organization
All of my scripts are maintained in a directory structure that I follow whenever I work on a site. The directory structure normally goes something like this:
+--root
|--javascript
|--lib
|--prototype.js
|--scriptaculous
|--scriptaculous.js
|--effects.js
|--..
|--myOwnScript.js
|--myOwnScript2.js
If, on the off chance, that I'm working on a team uses an inordinate amount of scripts, then I'll normally create a custom directory in which we'll organize scripts by relationship. This doesn't happen terribly often, though.
Compression
Though there are a lot of different compressors and obfuscators out there, I always come back to YUI Compressor.
Inclusion
Unless a site is using some form of a master page, CMS, or something that dictates what can be included on a page beyond my control, I only included the scripts necessarily for the given page just for the small performance sake. If a page doesn't require any script, there will be no script inclusions on that page.
First of all, YUI Compressor.
Keeping them organized is up to you, but most groups that I've seen have just come up with a convention that makes sense for their application.
It's generally optimal to package up your files in such a way that you have a small handful of packages which can be included on any given page for optimal caching.
You also might consider dividing your javascript up into segments that are easy to share across the team.
Cal Henderson (of Flickr fame) wrote Serving JavaScript Fast a while back. It covers asset delivery, not organization, but it might answer some of your questions.
Here are the bullet points:
Yes, you ought to concatenate JavaScript files in production to minimize the number of HTTP requests.
BUT you might not want to concatenate into one giant file; you might want to break it into logical pieces and spread the transfer cost over several pages.
gzip compression is good, but you shouldn't serve gzipped assets to IE <= 6, so you might also want to minify/compress your JavaScript.
I'll add a few bullet points of my own:
You ought to come up with a solution that works for both development and production. In development mode, it should pull in extra JavaScript files on demand; in production it should bundle everything ahead of time. Switching from one behavior to the other should be as easy as setting a flag.
Rails 2.0 handles all this through an asset cache; other web app frameworks might offer similar solutions.
As another answer suggests, placing third-party libraries in a lib directory is a good start. You can also divide your own JS files into sub-directories if it makes sense. Ideally, you'll be able to arrange them in such a way that the files in a given sub-directory can be concatenated into one file.
I will have a folder for all javascript, and a sub folder of that for 3rd party/shared libraries, and sub folders for each component of the site to keep everything organized.
For example:
/
+--/javascript/
+-- lib/
+-- admin/
+-- compnent1/
+-- compnent2/
Then run everything through a minifier/obfuscator during the build process.
I'v been using this lately:
http://code.google.com/apis/ajaxlibs/
And then have a "jscripts" folder where I keep my custom code.
In my last project, we had three kinds of JS files, all of them inside a JS folder.
Library code. A bunch of functions used on most all of the pages, so they were put together in one or a few files.
Classes. These had their own files, organized in folders as needed, but not necessarily so.
Ad hoc JS. Code that was specific to that page. These were saved in files that had the same name as the JSP pages they were supposed to run in.
The biggest effort was in having most of the code on the first two kinds, having custom code only know what to call, and when.
This might be a different approach than what you're looking for, but I've been playing around with the idea of JavaScript templates in our blog engine. In a nutshell, you assign a Javascript template to a page id using the database and it will dynamically include and minify all the JavaScript files associated with that template and create a file in a server-side cache with the template id as a file name. When a page is loaded, it calls the template file which first checks if the file exists in the cache and loads it if it does. If it doesn't exist, it creates it on the fly and includes it. I also use the template file to gzip the conglomerate JavaScript file.
The template idea would work well for site-wide JavaScript (like a JavaScript library), but it doesn't cover page-specific JavaScript. However, you can still use the same approach for page specific JavaScript by including a second file that does the same as above.

Categories