How do you re-use javascript functions - javascript

We have lots of javascript functions, which are usually handled via the onclick function. Currently they are present in every file where-ever it is needed. Would it make sense to consolidate all javascript functions into a single file and use this where-ever it is needed? What is the general practice here
<s:link view="/User.xhtml"
onclick="if (confirm('#{messages['label.user.warning']}')) {
var f = $('user');
f.method = 'POST';
f.action = f.submit();
} return false;">

Yes! Absolutely factor this out into an external javascript. Imagine if you needed to change something in this code. How many places do you have to change now? Don't duplicate code. It must makes your page bigger, which obviously affects how much is getting downloaded.

It's up to you to determine where the reusability lies in your own code. But it's easy enough (and a good idea) to create a library of often-used functions. Create a file like mylib.js, for instance, with things like...
function saveUser(f)
{
//...
f.method = 'POST';
f.action = f.submit();
}
add this to your pages:
<script type="text/javascript" src="mylib.js"></script>
add code your events like this:
<s:link view="/User.xhtml" onclick="return saveUser($('user'));">
Notice that the library code avoids any dependencies on the layout or naming of elements on the pages that use it. You may also want to leave little comments that will remind your future self what the purpose and assumptions of these library functions are.

Would it make sense to consolidate all javascript functions into a single file and use this where-ever it is needed?
Ummm...yeah
It would be better to do something like this:
function saveUser() {
// logic goes here
}
and use the markup
<s:link view="..." onclick="saveUser();">
Using code inline like that is very bad. Don't do it. Or the prorgamming gods will grow restless.

It is always a good idea to put JavaScript code in JavaScript files. Like you don't mix content and presentation (XHTML and CSS), you don't have to mix content and interactivity (XHTML and JavaScript).
Putting JavaScript code in a separate file has several advantages:
No need to duplicate code (so better reuse),
Possibility to minify the source code, thing which is quite impossible to do if you put together XHTML and JavaScript,
Ability to use non-intrusive JavaScript, helping to create more accessible websites (there is probably nothing wrong from the accessibility point to use onclick and other events, but it becomes very easy to forget that the website must work without JavaScript, thus developing a non-accessible website).
Better client-side performance: larger pages make things slower; when you put JavaScript outside, the pages are smaller, and the .js file is cached by the browser instead of being loaded on every request.

Javascript can be accessed via a script tag, which can point to an external script or define it for use in this document only.
<script type="text/javascript" src="mycustom.js"></script>
<!-- OR -->
<script type="text/javascript">
function saveUser(username) {
//code
}
</script>
No offense, but if you didn't know that you are either very new at this or you skipped a lot of steps in learning javascript. I recommend going through the w3schools.com tutorial on javascript and anything else you'll be using.

Related

What is the best way to organize JS code in webapps where the main "meat" is still server side?

When building webapps with MVC web framworks like Django, Kohana, Rails and the like, I put together the application without JS-driven components initially, and then add them afterwards as "improvements" to the UI.
This approach leads to non-intrusive JS, but I don't have a good "standard" way of how to go about organizing the JS work. Most of the JS I write in apps like these are 10-30 line JQuery snippets that hook into some very specific part of the UI.
So far I often end up inlining these things together with the part of the UI they manage. This makes me feel dirty, I'd like to keep the JS code as organized as the python / php / ruby code, I'd like for it to be testable and I'd like for it to be reusable.
What is the best way to go about organizing JS code in a setup like this, where we're not building a full-blown JS client app, and the main meat is still server side?
I am also very interested in what other people have to say about this. The approach I've taken is to use object literal notation to store the bulk of the function, and store these in one file included on all pages (the library)
uiHelper = {
inputDefault:function(defaulttext){
// function to swap default text into input elements
},
loadSubSection:function(url){
// loads new page using ajax instead of refreshing page
},
makeSortable:function(){
// apply jQuery UI sortable properties to list and remove non javascript controls
}
}
Then I include a .js file on any page that needs to use the library that ties the elements on that page to the function in the library. I've tried to make each function as reuseable as possible and sometimes the event binding function on the page calls several of my library functions.
$(document).ready(function(){
$('#mybutton').live('click',uiHelper.loadSubSection);
//more complicated helper
$('#myotherbutton').live('click',function(){
uiHelper.doThisThing;
uiHelper.andThisThing;
});
});
edit: using jsDoc http://jsdoc.sourceforge.net/ notation for commenting for these functions can produce documentation for the 'library' and helps keep your code easy to read (functions split by comments).
The following question is along similar lines to your own - you should check it out...
Commonly accepted best practices around code organization in JavaScript
When dealing with JS code, you should first analyze whether it will be used right away when the page loads. If it's not used right away (meaning the user must do something to invoke it) you should package this into a JS file and include it later so the load time is perceived faster for the user. This means that anything that the user will sees should go first and JS related to the functionality should be imported near the end of the file.
Download this tool to analyze your website: http://getfirebug.com/
If the JS code is small enough, it should just be inline with the HTML.
Hope that helps a bit.
For quick little user interface things like that I put everything into a single javascript file that I include on every page. Then in the javascript file I check what exists on the page and run code accordingly. I might have this in UIMagic.js for example. I have jQuery, so excuse those jQuery-isms if they aren't familiar to you.
function setupMenuHover() {
if ($("li.menu").length) { // The page has a menu
$("li.menu").hover(function() { ... }, function() { ... });
}
}
$(setupMenuHover);
function setupFacebookWizbang() {
if (typeof FB != "undefined") { // The page has Facebook's Javascript API
...
}
}
$(setupFacebookWizbang);
I've found this to be a sane enough approach.
My preferred method is to store inline javascript in it's own file (so that I can edit it easily with syntax highlighting etc.), and then include it on the page by loading the contents directly:
'<script type="text/javascript">'+open('~/js/page-inline.js').read()+'</script>'
This may not perform well though, unless your templating library can cache this sort of thing.
With Django you might be able to just include the js file:
<script type="text/javascript">
{% include "js/page-inline.js" %}
</script>
Not sure if that caches the output.
If you are still worried about being 'dirty', then you could check out the following projects, which try to bridge the server/client side language mismatch:
http://pyjs.org/ (Python generating JavaScript)
http://code.google.com/webtoolkit/ (Java generating JavaScript)
http://nodejs.org/ (JavaScript all the way!)

Is it right to write multiple and separate <script > on a page?

While writing JavaScript code, I Separate each code block with <script> tags
<script type="text/javascript">
//---- code block 1---------
</script>
<script type="text/javascript">
----code block 2-----
</script>
<script type="text/javascript">
$(document).ready.(function(){
// code block3
});
</script>
I want to know that is it good practice to write separate <script type="text/javascript"></script> on the same page
--or--
We have to write all JavaScript code under one <script>
What are the technical differences in each way?
Well, you may want to ask yourself why your code organization scheme leads to that setup, and whether it causes maintenance or understandability problems, but I don't think it's strictly "bad". Now if your <script> tags are actually fetching separate files from the server, then it's a good idea to cut back on them.
The browser parses and interprets script tags in such a way that other work stops, so blocks of Javascript up at the top of your page can slow things down if they do a lot of work. That's true whether you've got a big block of code or several smaller blocks, however.
An advantage of moving to separate script files is that you can re-use code on multiple pages. When you do that, it may be easier at build time to compress your scripts with YUICompressor or some other similar tool.
The best reason to do this is if each script represents a discrete chunk of functionality which may not be used on (and therefore not vended to) every page. In that case, it becomes a smart strategy.
Having multiple <script> tags makes no real difference in performance but is less readable.
There is one edge case where multiple script blocks can make a difference (and I just learned about it). If one line of code references a value before it has been declared, this will work if the code belongs to the same script block, but not if they are separate. But this doesn't change the answer everybody gave you: it probably won't matter in everyday coding.
You don't have to, but its obviously cleaner that way, unless you want to clearly seperate the blocks of code.
Put all your javascript coding in separate and then call the file name. Because it is good thing. Coding execution is step by step, so it will take time if js present in between the coding.
Not nice, but not a problem.
Hunter is right, it makes absolutely no difference as far as performance is concerned.
When your javascript however becomes more complex, you may want to start building your own API of sorts and splitting out all of those tags into separate files. Then when you're deploying your app, find some sort of packaging solution that will combine all of those files to a single one, compress it using YUI compressor or Google Closure and have one single tag that references this file of all your code.
While it is a 'slight' disadvantage to force a separate http request for this file, if it's packaged properly, the file size will be smaller than the uncompressed code you've included in that file.
It is also normal to have script tags further down in your page that provide extra functionality (ie look at google analytics)
Whenever you are violating the DRY principle (Don't Repeat Yourself), you need to ask why. If you don't have a good reason, then you probably shouldn't be doing it that way.

Where to put JavaScript configuration functions?

What is the general developer opinion on including javascript code on the file instead of including it on the script tag.
So we all agree that jquery needs to be included with a script file, like below:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript"></script>
My question is, in order to get functions on a page that is not on all pages of a site. Do we include the functions like below in the same page or in a global include file like above called mysite.js.
$(document).ready(function(){
$(".clickme").click(function(event){
alert("Thanks for visiting!");
});
});
ok. So the question is: if the code above is going to be called in every class="clickme" on a specific pages, and you have the ability to call it either from an include separate file called mysite.js or in the content of the page. Which way will you go?
Arguments are:
If you include it on the page you will only call it from those specific pages that the js functionality is needed.
Or you include it as a file, which the browser cached, but then jquery will have to spend x ms to know that that function is not trigger on a page without "clickme" class in it.
EDIT 1:
Ok. One point that I want to make sure people address is what is the effect of having the document.ready function called things that does not exist in the page, will that trigger any type of delay on the browser? Is that a significant impact?
First of all - $("#clickme") will find the id="clickme" not class="clickme". You'd want $(".clickme") if you were looking for classes.
I (try to) never put any actual JavaScript code inside my XHTML documents, unless I'm working on testing something on a page quickly. I always link to an external JS file to load the functionality I want. Browsers without JS (like web crawlers) will not load these files, and it makes your code look much cleaner to the "view source".
If I need a bit of functionality only on one page - it sometimes gets its own include file. It all depends on how much functionality / slow selectors it uses. Just because you put your JS in an external JS file doesn't mean you need to include it on every page.
The main reason I use this practice - if I need to change some JavaScript code, it will all be in the same place, and change site wide.
As far as the question about performance goes- Some selectors take a lot of time, but most of them (especially those that deal with ID) are very quick. Searching for a selector that doesn't exist is a waste of time, but when you put that up against the wasted time of a second script HTTP request (which blocks the DOM from being ready btw), searching for an empty selector will generally win as being the lesser of the two evils. jQuery 1.3 Performace Notes and SlickSpeed will hopefully help you decide on how many MS you really are losing to searching for a class.
I tend to use an external file so if a change is needed it is done in one place for all pages, rather than x changes on x pages.
Also if you leave the project and someone else has to take over, it can be a massive pain to dig around the project trying to find some inline js.
My personal preference is
completely global functions, plugins and utilities - in a separate JavaScript file and referenced in each page (much like the jQuery file)
specific page functionality - in a separate JavaScript file and only referenced in the page it is needed for
Remember that you can also minify and gzip the files too.
I'm a firm believer of Unobtrusive JavaScript and therefore try to avoid having any JavaScript code in with the markup, even if the JavaScript is in it's own script block.
I agreed to never have code in your HTML page. In ASP.net I programmatically have added a check for each page to see if it has a same name javascript file.
Eg. MyPage.aspx will look for a MyPage.aspx.js
For my MVC master page I have this code to add a javascript link:
// Add Each page's javascript file
if (Page.ViewContext.View is WebFormView)
{
WebFormView view = Page.ViewContext.View as WebFormView;
string shortUrl = view.ViewPath + ".js";
if (File.Exists(Server.MapPath(shortUrl)))
{
_clientScriptIncludes["PageJavascript"] = Page.ResolveUrl(shortUrl);
}
}
This works well because:
It is automagically included in my files
The .js file lives alongside the page itself
Sorry if this doesn't apply to your language/coding style.

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