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

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.

Related

How do you re-use javascript functions

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.

javascript in the <body>

I used to believe that you should not insert javascript blocks
<script language="javascript">
<!--
//-->
</script>
into the body part of a (what, HTML, XHTML?) document, but rather into the head.
But is that still true?
Script in the body (not links to external files) is like putting CSS in the head--people move toward separating it so that they can have the markup and logic separate for clarity and ease of maintenance.
I'm a big fan of the document ready feature of Jquery...but that's just personal preference. A dom loader is really the only way to guarantee loading is going to be identical between the various different browsers. Thanks, Microsoft!
I say use common sense...it's not worth doing another file for a single line of code...or even two. If we all went to the extremes that best practices sometimes ask us to go, we'd all be nuts.....or at least more nuts than we are now.
But is that still true?
I'm not sure it ever was. Are you thinking about <style> CSS elements? Because those are illegal in the body.
But it is usually the better choice to put Javascript code into the head or a separate script, and wrap it in a document.ready or onload event.
However, in-body Javascript can have its place, for example when embedding external JavaScripts that document.write() stuff into the document. Top-modern, bleeding-edge Google Analytics relies on a <script> segment being inserted into the very end of the body.
But is that still true?
It is a matter of good/best practices. HTML and Javascript should be separate. This is even knows as unobtrusive javascript/code.
More info at wikipedia:
Unobtrusive JavaScript
Although this is a good practice, but you can still put javascript at any part of the page, however you should avoid this as much as possible.
Some advocate that javascript should only go at the end of the page, for example they seem to say that is is better in terms of SEO (Search Engine Optimization) as well as performance as denoted by #David Dorward in his comment.
According to Yahoo, for the best performance it's recommended to put any script tags at the end of your document just before the closing html tags:
http://developer.yahoo.com/performance/rules.html
Google suggests using a deferred method to load scripts:
http://code.google.com/speed/page-speed/docs/payload.html#DeferLoadingJS
But they should almost always be script calls to an external .js file. There are very few occasions where it's better to have the .js embedded on the page.
It's not recommended because if you try to access elements in the body itself (i.e forms, fields, etc) since they may only become available once the entire body has rendered. However, it's a valid and actually very common practice.

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.

Tips on managing large amounts of code?

My project seems to be getting bigger and bigger and some of my classes are thousands of lines long. It's too hard to search through them every time I want to make changes.
I find JavaScript is not as easy to lay out cleanly as some other programming languages. So when the classes get to be a few thousand lines, I have troubles reading it.
I've tried splitting it into multiple files, but then you're breaking classes apart, which doesn't seem right. For example, if every method in a class uses a global variable, you would only be able to find the global variable in one of the files for that class.
Also, if I want to use the JavaScript code from 100 different .js files, I end up with something like this...
<script type="text/javascript" src="Scripts/classes/Node.js"></script>
<script type="text/javascript" src="Scripts/classes/Queue.js"></script>
<script type="text/javascript" src="Scripts/classes/DblyLinkedList.js"></script>
.... 97 more lines like this
Although, I figured there may be something where I can do...
<script type="text/javascript" src="Scripts/.../*.js"></script>
or something similar... is that right?
Anyone have any tips on managing code as it reaches its extremes?
Tips on cleaning up JavaScript code would also be helpful.
Breaking up JS into separate files has some major drawbacks, chiefly that you're forcing web browsers to make a separate request for each file.
Have you taken a look at leaving all of your files separated out, but making a single-file "bundle" for each project containing only the necessary files? This can be automated via a script.
This SitePoint article might help you get started: http://www.sitepoint.com/blogs/2007/04/10/faster-page-loads-bundle-your-css-and-javascript/
(a) keep your classes shorter [even
though that will mean yet more
files],
(b) keep them "full-text
indexed" for speed of search and
operation (not aware of any IDE
specifically supporting Javascript
this way, but strong editors like
Emacs, Vim, Eclipse, or TextMate sure
do),
(c) group them up hierarchically
so your pages can have just a few
<script> tags for "upper layer"
scripts each of which just pulls in
several of the "lower layer" ones.
Oh, and, of course, religiously keep everything under a good change control system (SVN, Mercurial, or the like), otherwise your life will be surely very very miserable:-(.
You might want to group related classes together into packages, where each package is a single file. Check out YSlow for best practices on performance.
Well, a good editor is always usefull, as it will give you shortcuts to all your functions defined in the files.
Second, make sure you're not looking at a wall of code. Indentation, spaces and newlines are a good help.
Be extremely strict in your indentation. 2 spaces is 2 spaces, always(or whatever amount you use)
if you put your { under a declaration, then always put it there, without exception)
Clear rules about how you want your text aligned will help a lot.
And I don't know about that last thing... I'm not sure browsers can work with that kind of wildcard.
<script type="text/javascript" src="Scripts/.../*.js"></script>
will not work, and besides, you end up with an interesting problem when splitting up dependent files, as you can't guarantee they will all be downloaded in the order you expected.
Unfortunately, your best bet is really a good IDE that can produce an outline for easy navigation. I use Eclipse with Spket and/or Aptana, but whatever makes it easier to manage is what you're looking for.
edit: one more quick note about splitting js into multiple files. Avoid it where possible. Each separate file means a separate http request. Reducing the number of requests required can make a massive difference in site performance.
AvatarKava's advice is sound. Work in separate files and concatenate them at build time. However, I would also recommend you take a look at your class structure. A class "thousands of lines long" doesn't sound too healthy. Are you sure you classes aren't taking on too much responsibility? Are there not tasks that can be shipped out to other single responsibility classes? This would help improve the clarity in your code far more than cunning ways of splitting files.
Same advice applies to most languages...
Avoid globals wherever possible. You can often get the desired behavior by wrapping a static variable, or using objects.
if (foo == undefined)
var foo
Use naming conventions where possible so you can track things down just by reading the variable or function names. Either that or get good with grep, or get an IDE with intellisense.
Split things into directories. Having 100 files in a directory called "classes" is not helpful. As an example, you may have a collections directory for queues, lists, trees, etc. If you've got a lot you may even have a tree subdir, or a list subdir, etc.
You can then also create a global include for that directory... simply a file called collections.js that includes all of the files in that directory. Of course you have to be careful about splitting things up well, since you don't want to be including files you'll never use.

Categories

Resources