Best practices for creating a reusable javascript web-app - javascript

I'm writing a web-app, using javascript, for the first time.
I was wondering what is the best method to make the web-app easily reusable, i.e. to make a "package" containing the js files, html and css, and load them like "load webapp"->launch it.
Currently I have an index.html which contains two divs:
the first one is a site-specific home page
the second one, initially hidden, is the panel of the web-app
once an initial selection is done in the homepage, I launch the app invoking a js method.
I'd like to make this more general, and I was wondering whether using jquery load() could be a clean solution (I'm currently using jquery). This would load the html, but I think I should still manually load the css in the page using the lib/app.
Any idea is appreciated.

Just make sure you don't embed any CSS or JS into your ASPX pages wherever possible, always keep them in separate files it'll be much easier to reuse certain aspects without having to dig around for the code. I've even seen JavaScript classes used to encapsulate a range of functionality, which could also be an option if you're that way inclined :).
In your said example, you're probably best calling a function in an external JS file on document ready.

Organizing your JS as JQuery plugins may also be an option for you. It may not make sense to put all of your JS into one plugin but if you split up your work into bite sized components this may make sense. Im not going to mention any particular resource because there are so many and I don't want to look like a spammer.
Hope this helps!

jQuery load won't help you organize your code, or load js dynamically, it has a complete other function (register to the onLoad event, or load an html page, or partial page via ajax)
If you're looking for dynamically load js libraries, use lab.js (at http://labjs.com) or require.js (at http://requirejs.org). But keep in mind that it can also be ok to have just one big js file that will get cached and load at once.
As far as organizing your js, it depends on the app. Sometimes jQuery plugin is the way to go. I had developed a solution that I am using on my projects, I just share it with you here: http://thebeast.heroku.com

Related

jQuery loading or appending scripts on specified page

Im a bit clules on the following situation, i am building a site, and right now all my js functions are in one js file, yes i know its a very bad idea.
What i am unfamiliar with, when i was checking other sites, i saw they include jQuery in the header and in the footer, different scripts are loaded.
I am unfamiliar, and please be nice i am a bit of a beginner.
Do people use some kind of plugin for this? or they include every script manualy in the specified file at the buttom?
I would like to break the scripts to parts, and not to include everything in one file.
What i mean by this, some functions only required in the profile page, some in the settings, and some in the login.
If someone could please give me some info about this would really help me.
Thank you
That's the sort of thing that one would use RequireJS for.
http://requirejs.org/docs/start.html
It will allow you to setup dependencies for your different JS files. These dependencies would then be loaded as needed.
Do people use some kind of plugin for this? or they include every script manualy in the specified file at the buttom?
Well, usually websites are made in PHP from individual components. Think of it as bricks. Some of these bricks contain JS code. When they are put together you end up with some pages having unique parts of javascript code in different places. It's not particularly good, but can dramatically simplify and speed up development.
I would like to break the scripts to parts, and not to include everything in one file.
Usually you want to include your JS with <script> tags in website header. If for some reason you'd like to dynamically include external JS then you may try to use this simple function: include();
i am building a site, and right now all my js functions are in one js file, yes i know its a very bad idea.
It's bad from development point of view, but when it comes to deploying the website it's a very good habit as it can decrease loading time of your website (and the loading time is one of most essential things). There are even applications compiling multiple .js files into a single minified file in order to get best performance.

Modular approach to client-side applications

This is a follow-up to my previous question.
Suppose there is a single web page with a login form and sign-up link. When a user clicks on the link a new sign-up form is displayed. Suppose also I create separate HTML, CSS, and JavaScript files for both forms for modularity.
Now the web page should contain some JavaScript code to load the login form, when the page is loaded, and load the sign-up form upon click on the link.
Does this approach make sense? Are there any frameworks/libraries, which implement this approach? How would you suggest implement it?
I think the idea has some issues. First you should know that there are some old fashion ways to load another completely separated page in the main document. Using "iframe" tag is one of the most popular and unsecure ways to do such a thing. Showing popups and use "window.open" is another way that can show a new window and load the specific url completely separated. BUT...
There are many reasons that I'm now gonna suggest you not to do that in any of mentioned ways. You can simply use some libraries like "JQuery" to load another html in the current page without any need to load new resources that cause performance issues for you. I believe you should search for "JQuery $.get" and you will see how easy it would be.
Hope it helps.
Cheers
Yes that makes sense to me. I really like this approach as I think breaking an app into smaller chunks will make the development & maintenance much easier.
Basicly you need to load the css and js files by appending a link and script tag respecticly into the head section of the html. For loading the html part of the module you can simply use jQuery.get() method as suggested by other answer.
I have tried to implement it. I recently released my work on this. a small code base. actually in my approach each module has its own folder with its js, html and css files and optionally a server-side file too like a php or aspx file that will be called by javascript to query the server.
here is the project page in github called Yuva
take a look and let me know if this makes sense to you.

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/?

jQuery page structure best practices for use of $(document).ready(function(){})

I currently have a lot of widgets on my website that do all sorts of jquery functions, animations, ajax calls etc. I have been reading online that it is good practice to try to bundle your js into one file when you can or when it makes sense. Each of my widgets are widely used on my website so it seems like it would make sense to put all the jquery/javascript for these widgets into one file. Now, if I have $(document).ready(function(){}) for everytime I want to invoke a widget's buttons, automatically load some data on doc ready, etc. what would be the best practice for doing this? Not every widget is on every page, so if everything was in one javascript file, would invoking dom elements that are non existent be bad practice?
I guess I am really having trouble seeing the best way to structure my jquery/javascript around my web application to provide best performance.
It is much better to keep js files filled with reusable code, so all your functions in one page that all pages load. I usually use default.js as that file.. then in each of the pages that require specific implementations i invoke the functions that performs specific tasks to that page, inside a doc.ready at the bottom of the page.
That way you're only doing what you need per page. In any case you should try to have functions that perform your tasks in the default.js file rather than very specific js in a file that is supposed to be generically included for the whole site

Where do you put your javascript?

Do you localize your javascript to the page, or have a master "application.js" or similar?
If it's the latter, what is the best practice to make sure your .js isn't executing on the wrong pages?
EDIT: by javascript I mean custom javascript you write as a developer, not js libraries. I can't imagine anyone would copy/paste the jQuery source into their page but you never know.
Putting all your js in one file can help performance (only one request versus several). And if you're using a content distribution network like Akamai it improves your cache hit ratio. Also, always throw inline js at the very bottom of the page (just above the body tag) because that is executed synchronously and can delay your page from rendering.
And yes, if one of the js files you are using is also hosted at google, make sure to use that one.
Here's my "guidelines". Note that none of these are formal, they just seem like the right thing to do.
All shared JS code lives in the SITE/javascripts directory, but it's loaded in 'tiers'
For site-wide stuff (like jquery, or my site wide application.js), the site wide layout (this would be a master page in ASP.net) includes the file. The script tags go at the top of the page.
There's also 'region-wide' stuff (eg: js code which is only needed in the admin section of the site). These regions either have a common layout (which can then include the script tags) or will render a common partial, and that partial can include the script tags)
For less-shared stuff (say my library that's only needed in a few places) then I put a script tag in those HTML pages individually. The script tags go at the top of the page.
For stuff that's only relevant to the single page, I just write inline javascript. I try to keep it as close to it's "target" as possible. For example, if I have some onclick js for a button, the script tag will go below the button.
For inline JS that doesn't have a target (eg: onload events) it goes at the bottom of the page.
So, how does something get into a localised library, or a site-wide library?.
The first time you need it, write it inline
The next time you need it, pull the inline code up to a localised library
If you're referencing some code in a localized library from (approximately) 3 or more places, pull the code up to a region-wide library
If it's needed from more than one region, pull it up to a site-wide library.
A common complaint about a system such as this, is that you wind up with 10 or 20 small JS files, where 2 or 3 large JS files will perform better from a networking point of view.
However, both rails and ASP.NET have features which handle combining and caching multiple JS files into one or more 'super' js files for production situations.
I'd recommend using features like this rather than compromising the quality/readability of the actual source code.
Yahoo!'s Exceptional Performance Team has some great performance suggestions for JavaScript. Steve Souders used to be on that team (he's now at Google) and he's written some interesting tools that can help you decide where to put JavaScript.
I try to avoid putting javascript functions on the rendered page. In general, I have an application.js (or root.js) that has generic functionality like menu manipulation. If a given page has specific javascript functionality, I'll create a .js file to handle that code and mimic the dir structure on how to get to that file (also using the same name as the rendered file).
In other words, if the rendered page is in public/dir1/dir2/mypage.html, the js file would be in public/js/dir1/dir2/mypage.js. I've found this style works well for me, especially when doing templating on a site. I build the template engine to "autoload" my resources (css and js) by taking the request path and doing some checking for the css and js equivalents in the css and js directories on the root.
Personally, I try to include several Javascript files, sorted by module (like YUI does). But once in a while, when I'm writing essentially a one-liner, I'll put it on the page.
Best practice is probably to put it on Google's servers.
(Depends what you mean by "your" javascript though I suppose :)
This is something I've been wrestling with, too. I've ended up by using my back-end PHP script to intelligently build a list of required JS files based on the content requested by the user.
By organizing my JS files into a repository that contains multiple files organized by purpose (be they general use, focused for a single page, single section, etc) I can use the chain of events that builds the page on the back-end to selectively choose which JS files get included based on need (see example below).
This is after implementing my web app without giving this aspect of the code enough thought. Now, I should also add that the javascript I use enhances but does not form the foundation of my site. If you're using something like SproutCore or Ext I imagine the solution would be somewhat different.
Here's an example for a PHP-driven website:
If your site is divided into sections and one of those sections is calendar. The user navigates to "index.phhp?module=calendar&action=view". If the PHP code is class-based the routing algorithm instantiates the CalendarModule class which is based on 'Module' and has a virtual method 'getJavascript'. This will return those javascript classes that are required to perform the action 'view' on the 'calendar' module. It can also take into account any other special requirements and return js files for those as well. The rendering code can verify that there are no duplicates of js files when the javascript include list is built for the final page. So the getJavascript method returns an array like this
return array('prototype.js','mycalendar.js');
Note that this, or some form of this, is not a new idea. But it took me some time to think it important enough to go to the trouble.
If it's only a few hundred bytes or less, and doesn't need to be used anywhere else, I would probably inline it. The network overhead for another http request will likely outweigh any performance gains that you get by pulling it out of the page.
If it needs to be used in a few places, I would put the function(s) into a common external file, and call it from an inline script as needed.
If you are targeting an iphone, try to keep anything that you want cached under 25k.
No hard and fast rules really, every approach has pros and cons, would strongly recommend you check out the articles that can be found on yahoo's developer section, so you can make informed decisions on a case by case basis.

Categories