Custom Lightweight JavaScript Libraries: EnderJS and MicroJS - javascript

I'm working on a custom lightweight JavaScript library that will need to run stably across the major browsers as well as across numerous independent sites without compromising or being compromised by existing libraries or namespaces. Perhaps most importantly, the library will need to be lightweight (~15k max).
UPDATE To clarify the need for such a small library: This is a third-party service that sites would pull into their page. We need to keep everything as light-weight, speedy, and self-contained as possible since we have no control over the existent libraries, speed, or page load. 15k is the target number just for the library that is accessed by the dynamic content of the service.
At this point my idea is to start with the most condensed jQuery-like base I can find, and then extend with custom modules.
Desired features:
Handle cross-browser inconsistencies like a champ (IE 6+, Chrome, FF 2+, Safari 3+).
Event handling (queuing/binding/broadcasting)
Efficient selector engine
Chaining
DOM manipulation w/ basic animations
Readily build-able and version-able from modules
I've come across EnderJS and MicroJS but I can't seem to find a lot of discussion on either. I'm more familiar and interested in Ender at this point since it seems to address all of the above features almost out of the box with "The Jeesh" weighing in at 7.5k. Tacking on a couple additional packages only pushes it to 10k in my case which would be perfect since I should only need a few k to flesh out any custom modules. It also would allow me to write and version distinct modules that can be incorporated and compressed into the main library at build-time, as well as define a unique namespace to hold it all together and hopefully protect it. Another compelling piece to the Ender library is its use of NodeJS which I would love to play around with more anyway. Having said all of that, however, I am still wide open to other ideas.
So my question is:
Does anyone have any experience with either EnderJS or MicroJS, or have another solution/approach to what I'm trying to accomplish? I realize this is not the place for "chatty, open-ended questions", and that's not my intent here. I'm just looking for suggestions on the best way to approach building a light-weight custom library without reinventing the wheel and to instead plug into the most up to date micro-libraries available.

I'm one of the co-creators of Ender and I'll +1 Fazal's words.
A note on the Jeesh, albeit a nice starter-pack to Ender, the true power lies in the ability to extend Ender with its growing set of modules. You can check them out here: https://github.com/ender-js/Ender/wiki/Ender-package-list
Somehow, one way or another Ender became the forefront of "micro library" development, but really what we're after is putting a cohesive interface onto loosely coupled modules (however large or small they are). jQuery took a great first step in abstracting its selector engine (Sizzle), but unfortunately the rest of it is interdependent (dom, events, animation, ajax, utils, promises), thus making it impossible to pick and pull what you want.
On another aside, one of the neat things about Ender is the ability to publish modules to NPM and being able to port them into your project by name allowing you to build only what you need, when you need it
It's worth checking out the learn videos at http://enderjs.com/learn which will give you a better idea of how packages are authored, built, and consumed. You'll find that setting up Ender into your environment is extremely simple and actually quite fun to work with.
Let us (#ded or #fat) know if you have any questions and we'll be more than willing to help sort things out

I've used Ender recently, and I've had no issues with it really. There are a couple of jQuery functions that aren't available from the off, but anyone who is fairly adept at JavaScript can circumvent this. Especially given the fact that Ender has a near identical structure and way of extending as jQuery.
I've used Ender on a live site recently and funnily enough I have used a couple of scripts from microjs.com alongside my own functions file, and all the JavaScript weighed in at around 15k. It's not hard to make your entire site code weigh around that or less.
As well as building a lightweight version of Ender, for example starting with the Jeesh, you might also want to consider async loading, an example is provided by Dustin Diaz:
<script src="ender.min.js"></script>
<script>
$.require('/js/core.min.js', 'core')
$.ready('core', function () {
$(document).ready(function () {
$('<p>hello world</p>').appendTo('body')
.bind('click', function (e) {
$.require('/js/ajax.min.js', function () {
$(e.target).css('position', 'relative')
.animate({
left: 500
})
})
})
})
})
</script>
By doing this you could essentially make the original ender build even lighter, and defer some of the loading, but generally speaking, if it's light in the first place you should be ok.
You might also want to take advantage of the Google closure compiler that Ender gives you access to in order to compile your site code alongside ender.
Finally, as you're probably well aware, you can do noConflict in Ender as well, just in case they already have another library present.
As you build and configure Ender you will probably want to take advantage of ender-wallet which will give you a sort of API view, allowing you to remove libraries you might not need at all.
hotlinked screenshot:

Given this:
To clarify the need for such a small library: This is a third-party service that sites would pull into their page. We need to keep everything as light-weight, speedy, and self-contained as possible since we have no control over the existant libraries, speed, or page load. 15k is the target number just for the library that is accessed by the dynamic content of the service.
I'd recommend using demand-loaded jQuery via one of the CDNs (Google's or Microsoft's; I think Google's is used more but you'd want to test). Your code can detect whether jQuery is already loaded and use it if so (~0k), and if not add a script element dynamically that pulls it from the CDN. If the user has visited any other site using jQuery from that CDN, then the script may well come from cache (~0k). If not, granted, then you have the ~31k rather than ~15k hit, but again, quite frequently you won't have any hit, or just the hit of a "not modified" response from the CDN.
You'd want to issue a noConflict call if you did load it, in case the site uses $ for something other than jQuery. That's readily done by watching for the load event on the script element (you have to use readystatechange on IE and watch for either loaded or complete status) and then doing it when that comes through.
In today's telecomms world, the difference between a 15k download and a 31k download is trivial compared with the cost of setting up the HTTP connection in the first place.
That demand-load really is a tiny bit of code, along these lines:
function loadJQuery(cb) {
var d, s, t;
if (typeof jQuery === "function"
&& parseFloat(jQuery.fn.jquery) >= 1.5) { /* Or whatever */
window.ourjQuery = jQuery;
if (cb) {
cb();
}
return;
}
d = document;
s = d.createElement('script');
t = d.body || d.getElementsByTagName('head')[0] || d.documentElement;
s.onload = loaded;
s.onreadystatechange = handleReadyStateChange;
s.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
t.appendChild(s);
function loaded() {
if (s) {
s = undefined;
window.ourjQuery = jQuery.noConflict(true);
if (cb) {
cb();
}
}
}
function handleReadyStateChange() {
if (s && (s.readyState === "loaded" || s.readyState === "complete")) {
loaded();
}
}
}
Note the URL on the script element. That's so it's friendly to both http and https pages (details). Note also that I'm checking for a minimum jQuery version and using the more rigorous form of noConflict if we load it. Either way, by the time the callback is called, the ourjQuery symbol refers to the loaded copy with the minimum version.
Update: Addressing your comment above:
That's a good idea but unfortunately not really an option for us. I agree jQuery from Google's CDN would most likely be cached - saving load - and that we could check and extend as needed, but it doesn't seem as scalable or stable as serving it ourselves. The site could decide to overwrite some jQuery module to suit their needs or worse. What we need is a light-weight self-contained library that we have complete control over and can extend and branch as needed. The goal is that this library will be cached and versioned from our CDN.
Yes, there's a small risk of a site having modified basic jQuery functionality. A very small risk. If you're restricting yourself to the core API (not plugins and such) I frankly don't think it's worth worrying about.
But if you're worried about that, then frankly I'd just use a slightly-modified jQuery hosted on your own CDN using a different symbol than jQuery (and not using $ at all). 31k vs. 15k in today's telecomms world is a non-issue; the primary cost will be in establishing the connection in the first place. If you wanted, you could probably pare that down a bit by removing parts you don't need, although sadly the jQuery internals are a bit of a morass and selectively removing functionality may not be trivial (depending on what functionality it is).

Related

How much is the negative affect on performance due to loading and using jQuery?

I do a little bit of third party javascript work for a company where I am able to enter my javascript snippets into the CMS and have it run in the customer facing sites.
I have the option to switch on JQuery 1.7.1 in the header of the site and I usually choose to do this or not depending on how much more complicated it would make my code if I didn't.
I have often wondered how much difference it would make if I just turned it on in all cases so even simple things like:
document.getElementById('myElement');
became
$('#myElement');
Where would the 'breakpoint' be in deciding it was better / more efficient / easier to switch on JQuery?
Today's example that made me think of this was as follows (both regular javascript followed by the JQuery equivalent ):
Javascript:
if (document.getElementById('myElement')!== null) {
var oldText = document.getElementById('myElement').innerHTML,
newText = oldText.replace(/one/i,'two');
document.getElementById('myElement').innerHTML = newText;
}
jQuery:
if ($('#myElement').length !== 0) {
var oldText = $('#myElement').html(),
newText = oldText.replace('one','two');
$('#myElement').html(newText);
}
And How much is the negative affect on forcing the clients to download jQuery?
The difference will be minimal, and not worth writing those 10 chars...
As always, remember that as a developer, your time is typically the most valuable resource. Do not focus on optimization of selector speed unless it is clear that performance needs to be improved.
jQuery site
And of course jQuery has a lot more features than id selectors...
A good advise is to cache the queried elements and not query them multiple times, but it's true both with jQuery and with vanilla javascript;
From:
document.getElementBy('id').value = "foo";
document.getElementBy('id').parentNode.className = "parent";
To:
var element = document.getElementBy('id')
element.value = "foo";
element.parentNode.className = "parent"
or jQuery version:
var $element = $('#id');
$element.val("foo");
$element.parent().addClass("parent");
Due to jQuery "chainabilty" - cascading styile, you do that with one "chain":
$('#id').val("foo").parent().addClass("parent");
This jsperf shows that $('#id') is 3-6 slower than document.getElementById
Which means you can have "only" 1,000,000 those operations per second... "A disaster"!
"We should forget about small efficiencies, say about 97% of the time: premature 
optimization is the root of all evil"
Regarding to the "loading"- downloading time of the jQuery library.
The current minified version of jQuery (1.7.2) size is only 32K, which is almost for sure smaller than most of images in your website, so it's negligible.
You can use google global cached copy of jQuery, read more about it in this long blog post.
No matter how well optimized your site is, if you’re hosting jQuery locally then your users must download it at least once. Each of your users probably already has dozens of identical copies of jQuery in their browser’s cache, but those copies of jQuery are ignored when they visit your site.
However, when a browser sees references to CDN-hosted copies of jQuery, it understands that all of those references do refer to the exact same file. With all of these CDN references point to exactly the same URLs, the browser can trust that those files truly are identical and won't waste time re-requesting the file if it's already cached. Thus, the browser is able to use a single copy that's cached on-disk, regardless of which site the CDN references appear on.
Your plain JS could be a lot more efficient itself without adding jQuery:
var obj = document.getElementById('myElement');
if (obj) {
obj.innerHTML = obj.innerHTML.replace(/one/i,'two');
}
Anytime you're repeating the same selector operation multiple times within the same function you should generally cache it into a local variable and you have no need for either of your other temporary variables here.
FYI, if you want a shortcut for getElementById(), you can define your own very easily without including a whole library just for that.
window.$ = function(id) {
return(document.getElementById(id));
}
There are also much, much smaller libraries than jQuery that gives you basic selector operations. jQuery itself uses the Sizzle library which is often what I use when I just want selector operations.
I'm not arguing against jQuery if you use/need many of the things that it offers. It's particularly useful for ajax and many DOM manipulation functions. But, if your needs are simple, there are often more efficient ways of doing things than including all of jQuery if site efficiency/speed/size is important.

Dojo require() and AMD (1.7)

I'm having a heckuva time transitioning to Dojo and the new AMD structure, and I'm really hoping someone can shed some light on the whole concept. I've been living on Google for the last few weeks trying to find information on not the usage, but the structure and design pattern trends in using this.
I find it strange that for a relatively complex javascript application, such as for a main page where Dijits need to be created and styled, DOM elements created, etc, that I need to require, and therefore use, a TON of different modules that were otherwise available in the dojo namespace before the AMD system (or, at least, not assigned to 23 different vars).
Example:
require(['dijit/form/ValidationTextBox', 'dijit/form/SimpleTextarea', 'dijit/form/CheckBox', 'dijit/Dialog', 'dijit/form/Form'])
require(['dojo/ready', 'dojo/parser', 'dojo/dom-style', 'dijit/registry', 'dojo/dom', 'dojo/_base/connect', 'dojo/dom-construct'],
function(ready, parser, style, registry, dom, event, construct){
//...etc
}
That's only a few of the modules for one of the pages I'm working on. Surely there's a better, non-breaking-in-future-releases way of accessing these methods, etc. I mean, do I really have to import an entirely new module to use byId()? And yet another to connect events? On top of that, all the clutter being created by having to assign a variable name in the functions argument list to cling to just seems like such a backstep.
I thought maybe you would require() the module only when needed, such as the query module, but if I need it more than once, then chances are the variable it's assigned to is out of scope, and I'd need to put it in a domReady! or ready call. reaalllly....??!
Which is why I can only assume it's my lack of understanding for dojo.
I really have looked and searched and bought books (albeit, a pre-AMD one), but this library is really giving me a run for my money. I appreciate light anyone can shed on this.
Edit for Example
require(['dijit/form/ValidationTextBox'])
require(['dojo/ready', 'dojo/parser', 'dojo/dom-style', 'dijit/registry', 'dojo/dom', 'dojo/_base/connect', 'dojo/dom-construct'], function(ready, parser, style, registry, dom, event, construct){
/* perform some tasks */
var _name = new dijit.form.ValidationTextBox({
propercase : true,
tooltipPosition : ['above', 'after']
}, 'name')
/*
Let's say I want to use the query module in some places, i.e. here.
*/
require(['dojo/query', 'dojo/dom-attr'], function(query, attr){
query('#list li').forEach(function(li){
// do something with these
})
})
}
Based off of this format, which is used with many examples both from the dojo toolkit folks as well as third party sites, it would be, IMHO, absolutely ridiculous to load all the required modules as the first function(ready, parser, style, registy... would get longer and longer, and create problems with naming collisions, etc.
Firing up and require()ing all the modules I would need during the life of the script just seems silly to me. That being said, I'd have to look at some of the "package manager" scripts. But for this example, if I wanted to use the query module in select places, I would either have to load it up with the rest in the main require() statement. I understand why to an extent, but what's so bad with generic dot-syntax namespaces? dojo.whatever? dijit.findIt()? Why load module, reference in a unique name, pass through closure, blah blah?
I wish this were an easier question to ask, but I hope that makes sense.
Exasperation
Call me a newb, but this is really.. really.. driving me mad. I'm no noob when it comes to Javascript (apparently not) but wow. I cannot figure this out!
Here's what I'm gathering. In adder.js:
define('adder', function(require, exports){
exports.addTen = function(x){
return x + 10
}
})
In some master page or whatever:
require(['./js/cg/adder.js'])
...which doesn't follow the neat require(['cg/adder']) format but whatever. Not important right now.
Then, the use of adder should be:
console.log(adder.addTen(100)) // 110
The closest I got was console.log(adder) returning 3. Yep. 3. Otherwise, it's adder is not defined.
Why does this have to be so difficult? I'm using my noob card on this, cause I really have no idea why this isn't coming together.
Thanks guys.
The dependency array format:
define(["a", "b", "c"], function (a, b, c) {
});
can indeed be annoying and error-prone. Matching up the array entries to function parameters is a real pain.
I prefer the require format ("Simplified CommonJS Wrapper"):
define(function (require) {
var a = require("a");
var b = require("b");
var c = require("c");
});
This keeps your lines short and allows you to rearrange/delete/add lines without having to remember to change things in two places.
The latter format will not work on PS3 and older Opera mobile browsers, but hopefully you don't care.
As for why doing this instead of manually namespacing objects, #peller's answer gives a good overview of why modularity is a good thing, and my answer to a similar question talks about why AMD and module systems as a way of achieving modularity are a good thing.
The only thing I would add to #peller's answer is to expand on "paying attention to dependencies actually makes for much better code." If your module requires too many other modules, that's a bad sign! We have a loose rule in our 72K LOC JavaScript codebase that a module should be ~100 lines long and require between zero and four dependencies. It's served us well.
requirejs.org gives a pretty good overview of what AMD is and why you'd want to use it. Yes, Dojo is moving towards smaller modules which you would reference individually. The result is that you load less code, and your references to it are explicit. Paying attention to dependencies actually makes for much better code, I think. AMD enables optimizations, and once the migration is complete, you don't have to load everything into globals anymore. No more collisions! The require() block wraps the code which uses various modules. domReady! relates to the loading of the DOM and has nothing to do with variables being in scope.
Anyway, this is deviating from the Q&A format of SO. You might want to ask specific questions.

Best practice for using JavaScript in Django

I want to push my Django project with some JavaScript/jQuery. To make it right from the beginning on I'd like to know, which way of organizing the .js-files ist the optimal one.
For loading one big file includes less overhead than loading many small ones and also because it looks cleaner in the code I considered to make one global .js-file and include that with the base.html (from which every template inherites). However, the result would be, that JavaScript would try to assign all the event-binings, even if the elements which the events should be bind to aren't in the current document. With all the jQuery-selectors which then would have to do their work that can't be too efficient. From earlier web-development experience I know that one can do something like if(location.href == '/some/url/') { (JavaScript code) ... }. That seems not practicable for me in this case, for with changing URLs, I'd have to change the URLconf and the .js-file (while using reverse() and {% url %} to prevent that elsewhere). I guess there is no possibility to make use of the named URLs here?
Has anyone an idea how to organize the JavaScript without having a file for every single template on the one hand and without killing performance unnecessarily?
I don't know that this question is specific to Django - similar issues come up managing Javascript in all sorts of systems.
That said, I usually try to tier my Javascript files, so that truly global scripts and libraries are included in one file, scripts specific to a section of the site are included in a set of section-specific files, and scripts specific to a single page are included in yet another site of page-specific files (or in inline code, depending on the context).
Django has good support for this approach, because you can tier your templates as well. Include the global script in your base.html template, then create a mysection-base.html template that inherits from base.html and just adds the Javascript (and CSS) files specific to that section. Then subpages within that section can inherit from mysection-base.html instead of base.html, and they'll all have access to the section-specific scripts.
I find django-compressor invaluable as it automatically compresses and minifies your JavaScript and CSS pre-deployment. It even automatically handles SASS, LESS and CoffeeScript if they float your boat.
Apps from http://djangopackages.com/grids/g/asset-managers/ may help.
You use modular javascript.
Choose your packager of choice (mine is browserify) that packages all your modules into one package that you minify and gzip. You send this file to the client and it is cached.
This means you have all your code cached, minimize HTTP requests and stay lean and efficient.
And since you have modular code you just load your code as you would normally.
Personally I would use some form feature detection to load modules. You can choose to feature detect on almost any feature (some css selector, routes, url segments).
Feature detection would look like this :
var Features = {
"class": "name",
"class2": "name2",
"dynamic-scroll": "dynamic-scroll",
"tabstrip": "tabstrip",
...
}
for (var key in Features) {
require(Features[key]);
}
Where as routing with davis would look like
Davis(function() {
this.get("blog", function(req) {
require("blog")(req);
});
this.get("blog/:post", function(req) {
require("blog-post")(req);
});
this.get("shop", function(req) {
require("shop")(req);
});
...
});
Alternatively you can try an event driven architecture. This means each module binds to events
// some-module
mediator.on("blog-loaded", function() {
// load in some libraries
// construct some widgets
mediator.emit("blog-ui-build", widgets);
});
And you would need some bootstrapping in place to kick off the event loop. Feel free to look at an EDA demo

How do you organize your Javascript code?

When I first started with Javascript, I usually just put whatever I needed into functions and called them when I needed them. That was then.
Now, as I am building more and more complex web applications with Javascript; taking advantage of its more responsive user interaction, I am realizing that I need to make my code more readable - not only by me, but anyone who replaces me. Besides that, I would like the reduce the moments of 'what the heck, why did I do this' when I read my own code months later (yes, I am being honest here, I do have what the heck was I thinking moments myself, although I try to avoid such cases)
A couple weeks ago, I got into Joose, and so far, it has been good, but I am wondering what the rest do to make their chunk their codes into meaningful segments and readable by the next programmer.
Besides making it readable, what are your steps in making your HTML separated from your code logic? Say you need to create dynamic table rows with data. Do you include that in your Javascript code, appending the td element to the string or do you do anything else. I am looking for real world solutions and ideas, not some theoretical ideas posed by some expert.
So, in case you didnt't understand the above, do you use OOP practices. If you don't what do you use?
For really JS-heavy applications, you should try to mimic Java.
Have as little JS in your HTML as possible (preferably - just the call to the bootstrap function)
Break the code into logical units, keep them all in separate files
Use a script to concatenate/minify the files into a single bundle which you will serve as part of your app
Use JS namespaces to avoid cluttering up the global namespace:
var myapp = {};
myapp.FirstClass = function() { ... };
myapp.FirstClass.prototype.method = function() { ... };
myapp.SecondClass = function() { ... };
Using all these techniques together will yield a very manageable project, even if you are not using any frameworks.
I use unobtrusive javascript, so, outside of the script tags I don't keep any javascript in the html.
The two are completely separated.
A javascript function will start when the DOM tree is completed, which will go through the html and add the javascript events, and whatever else needs to be changed.
In order to organize, I tend to have some javascript files that are named similar to the html pages that they use, and then for common functions I tend to group them by what they do, and pick a name that explains that.
So, for example, if I have UI functions then I may call them: myapp_ui_functions.js
I try to put the name of the application in the filename, unless there is some javascript that is common to several projects, such as strings.js.
I have (usually) one file that contains a bunch of functions and that's it. That is included in every page that uses Javascript. In the pages themselves, I'll make the calls to the functions like:
$(function() {
$("#delete").click(delete_user);
$("#new").click(new_user);
});
where delete_user() and new_user() are defined in the external file.
I too use unobtrusive Javascript, which for me means jQuery (there are other libraries that are unobtrusive).
You don't want a separate file for each page. That just means more unnecessary external HTTP requests. With one file—assuming you've cached it effectively—it'll be downloaded once and that's it (until it changes).
If I have a large amount of Javascript or the site is effectively split into multiple areas then I may split the Javascript but that's not often the case.
Also, in terms of my source code, I may have multiple JS files but I'll often end up combining them into one download for the client (to reduce HTTP requests).
More at Multiple javascript/css files: best practices? and Supercharging Javascript in PHP.
I've been rewriting a lot of my reusable code as jQuery plugins. I moved to jQuery from Prototype when I started doing ASP.NET MVC. Overtime I've migrated a lot my reusable code, or at least the ideas, from Prototype-based OO to jQuery-style plugins. Most of these are stored in their own JS files (mainly intranet apps so page load speed is pretty high anyway despite the extra requests). I suppose I could add a build step that coalesces these if I needed to.
I've also settled on a MasterPage approach that uses a ContentPlaceHolder for scripts that is right before the closing body tag. The standard jQuery/jQuery UI loads, and any other common JS goes right before the script placeholder in the MasterPage. I have tiny bit of JS at the top of the MasterPage that defines an array that holds any functions that partial views need to run on page load. These functions are run from the base document.ready() function in the MasterPage.
All of my JS is completely separate from my mark up. Some JS may exist in partial views -- these are encapsulated when the partial may be included more than once to make it specific to that instance of the view -- but generally not. Typically only included in the placeholders so that it's loaded at the bottom of the page.
Also, if you want to go OO heavy, check out mochikit: http://www.mochikit.com/
I find that developing your javascript using OO methodology is the way to go if you want it to be clean, readable and even somewhat secure. I posted the following question
Cleanest format for writing javascript objects
And got some fantastic responses on how to write my javascript code well. If you follow these basic principles you can use almost any library, such as yui, jquery and prototype, with ease.

Splitting code in to multiple files for easier management

I am currently using jQuery to write an online application, that started off with a couple of lines of code, and have quickly now become over a 1000 lines.
My code's structure is simple. I have a window.load which wraps my javascript, and inside it I start adding my click event handlers, and the various functions that makeup my application.
$(window).load(function(){
// Code goes here...
});
My code functions can definitely be grouped into categories; e.g. 5 functions perform animation, 12 are event handlers, etc.
I would like to group the functions in their own js files, and import them individually. I can later use my CMS engine to concatenate and compress the files on the fly.
What is the best way in doing so. I am thinking that maybe I can give some of my functions their own namespace for further clarity; e.g. all animation functions are prefixed with ANIMATION - ANIMATION.moveDiv1(), ANIMATION.moveDiv2, MYEVENT.div1Clicked, etc.
I generally stick all related items into their own file, with a namespace that matches the file for readability sake.
An example file could look like:
Example.js
var Animation = {}; // create the namespace-like object
Animation.moveDiv1 = function() {...};
Animation.moveDiv2 = function() {...};
There's really a lot of ways to do this. Speaking of compression, there are some nice tools that you can use to compress things. Check out YUI Compressor
Modularity is a good goal with Javascript, but I would say the next level would be to actually use some Javascript OO techniques. If your app is simple enough, you can probably do without it though.
Your code files should mirror your classes.
Your classes should follow principles of good OO design.
In terms of load-time within the browser, kekoav and knut have the right idea - just use YUI or another script compressor/minifier (and optionally an obfuscator), combine them into a single file and load them all from a single script include directive.
I'd also have a look at JS the prototype property of your classes - if they're getting large and you're creating multiple instances of them, you'll start to see significant performance gains by putting your public (and optionally, private/privileged) methods into the class prototype.
You should definitely be using fully-qualified namespaces for your classes, either using Microsoft's Type.registerNamespace if you're using their AJAX solution, by declaring your own namespace functions as per kekoav's post, or using a squillion other similar approaches that Google will offer.
Good idea from a standpoint of application management, bad idea from the standpoint of loading time. The browser has to load all those little scripts synchronously, therefore taking more time for each additional script you want to load. That's not including the main jQuery library script, the jQuery UI and whatever else you plan on having in your document. Test both premises: abstracting functions out into their own individual scripts and load them vs. one big script that only requires one call to load. Take it a step further and minify the "one big script", one more step and make sure it's served as a compressed file.
You may split the JavaScript files into classes when you are developing, but you should combine your scripts, and minimize them in a production environment. Please take a look at YUI Compressor for more information.

Categories

Resources