Which technique is better? - javascript

Which technique is better:
<span onclick="dothis();">check</span>
or:
<span class="bla">check</span>
<script type="text/javascript">
$('.bla').click(function(e) {} );
</script>
Are there any differences according to usability, performance etc.?
Thank you!

The second is better from a code quality standpoint since it is considered to be unobtrusive. I am not certain if either approach has measurable performance benefits.
My advice is to stick to the unobtrusive approach - it will save you a lot of time when you are doing maintenance down the road.

The second is much better. See Unobtrusive JavaScript

Always better to keep your script OUT of the DOM.

Technique 1 is intrusive or obstrusive JavaScript: Your markup is intermixed with your JavaScript calls, which can be really messy and is not a separation of concerns.
Technique 2 is unobstrusive: Your JavaScript is kept separate from the markup, keeping both clean but adds a lot of boilerplate code.
Neither is better, although Technique 2 works better for larger projects for me, but always requires looking in two places and can introduce bugs by changing the markup but not the JavaScript.

You should always try and do the best thing which, for most scripts is to put it in a separate file. If it's a small script, like your example, then it's actually going to be quicker to put it in <script> tags in the document head.
Always steer clear of onClick="" and friends; it makes for messy, sometimes repetitive code and can be hard to maintain/debug.
Another note: if your script is huge (100s of lines), the extra time it takes for the browser to fetch the external file is compensated by the fact the script isn't in the HTML, so it will load the same or faster. For small scripts that won't go beyond say a maximum of 50 lines will be fine in the <head>.

In my opinion, the first approach is easier to debug, it is very clear that dothis() is called when you click on the span; it is harder for the second especially when you put the event handling code into a javascript file. For performance, i think it is tiny, although the first one absolutely have better performance.

Related

Store HTML code in variable (faster for the browser?)

Is there a difference between ...
this
<html>
...
<div id="myDiv"> </div>';
...
</html>
var manyHtmlCode = ' ... many Html Code ... ';
// onclick -> write it in to the DIV -> $('myDiv').append(manyHtmlCode);
and this
<html>
...
<div id="myDiv" style="display:none;"> ... many Html Code ... </div>';
...
</html>
// onclick -> show content $('myDiv').show();
It is obvious to me that the second solution is faster in javascript, but what about with the browser speed?
Is the browser faster (for example, draging a div) with a smaller HTML code in the body Tag?
If so, it would be better to store not needed HTML code in a JS var. My Problem is that i have a page with many many draggable divs. Imho is the dragspeed better when the html code is smaller.
The second solution is faster for two reasons:
The HTML in this approach is 'static' HTML; it exists in the response to the browser, and doesn't need to be parsed or interpreted by JavaScript to get added to the page.
When parsing and rendering the HTML, the browser will notice the display: none and not bother rendering that element nor anything inside it. This speeds up the initial render of the page, because it doesn't actually render a lot of your HTML.
I would use second one, because it is faster to execute. (1 call of jQuery instead of 2)
If you have too many DOM items then i would suggest go with first one.
Suppose you want to traverse DOM and look for an element , if you have less elements then traversing will take less time.
My suggestion is to benchmark your code. And use the one that suits best to you.
You can use below tool
http://jsperf.com/
Depends on what exactly you wanna achieve. Yes the second one would obviously be faster as the HTML is already present in the Document, which the jQuery unhides. While in the 1st method the jquery is writing the content in real time.
Again there may be different ways to achieve what you are trying, like you could write divs u have edited into a file using ajax etc etc .. and remove it from the current document. Thus reducing the amount of html in the document.
I'm just giving you an idea here.. the thing is u haven't clearly explained what you are trying to achieve to give you the most suitable solution
Is there a difference between ...
It depends on the meaning of "is".
On a particular version of a particular browser, one or the other will run faster. You can, if you wish, benchmark them on five or 10 different browser versions and find out which usually wins.
But so what? The user won't be able to tell the difference; the user's computer typically isn't doing anything else, so there's no point in conserving the CPU cycles.
My advice to all programmers -- but especially to programmers writing for browsers -- is to ignore time and space efficiency until you see a problem and focus on
Correctness -- the code performs as designed, even in the face of unexpected inputs, changes in the underlying platform, and similar challenges;
Maintainability -- the code is written so it can be altered as requirements change; and
Usability -- the code presents an interface (either the UI in the case of end-user code or API in the case of library code) that allows a user who lacks a complete appreciation of the code to still use it correctly.
Efficiency, bah.

Is it good to use more than one forms on a page?

I want to use multiple forms in one page in my project because RightJS have many good methods for AJAX form handling. But I am afraid that it will lead to problems with speed.
Does it really so?
Having multiple <form> elements can be better for performance, since you're not submitting useless information outside the scope you care about with each submit.
Use as many as appropriate - the units that your information is submitted in, that should be the scope of a particular <form> element, so you're dealing with and submitting only the information you care about with each action.
It's both semantically and performance wise a good move. At the same time, don't go completely overboard and have 100 forms, unless there are actually 100 units of work.
Speed will not be affected by having multiple forms on a page.
As long as multiple forms don't result in bad usability it's fine - why do you think they'll lead to speed problems (they don't unless you maybe have 1000 forms on your page which you hopefully don't plan to do anyway)?
Basically, as good people of stackoverflow already told you, in most cases it will be just fine, but I tell you what. The best way to answer a question like "will it be slow or not" is to implement the thing.
Just write a simple loop, generate a bunch of things on the page and see what happens. In many cases there are too many variables and hidden issues to say for sure what will happen. A little bit of an old fashioned experiment will give you more than hours of wondering around :)

Jquery - More than 1 "$(document).ready" = dirty code?

is it OK to use the
$(document).ready(function ()
{
// some code
});
more than 1 time in the javascript code?
Yes, it is OK, jQuery will queue and merge them into a single handler called when the DOM is ready.
Sure it is ok. Sometimes you have no other option. especially when you have some included JS files with jQuery and some jQuery code in the page itself.
I find that having everything in one huge $(document).ready leads to messy code thats hard to read.
I often prefer to split it up and place a separate $(document).ready() for every part of the system that needs stuff added to it. This is especially nice for larger, modular, systems, where you dynamically add blocks of html, events and stuff.
For me it all boils down to what is most beneficial for you as a developer in a certain case.
Small system, where it's easy to know what's going on: one $(document).ready() in your script.
Large, modular, system: split it up as needed to have control of what's going on, and develop efficiently.
But as #Codesleuth commented: very often you don't need to put stuff inside the $(document).ready(), you only need it when you need to be sure the DOM is in a consistant and known state for heavy manipulation etc.

Attaching events in JavaScript

As comment to one of the questions here a commenter wrote (emphasis mine):
... By using an inline "onclick" you are doing a similar thing, but it is harder to maintain and more prone to issues. The JavaScript community as a whole has been moving away from inline JavaScript for a while now.
This was referring to attaching events to HTML elements using:
$("#someID").click(function(){
do something here...;
});
rather than:
<a id="someID" onclick="someFunction();">
Has there really been a shift away from the old school way of declaring events inline, and if so, what are the benefits of one of the other?
EDIT I guess it may be helpful to include a reference to the original question. It asked about attaching a different click event to each tab. Is my answer crap and do I owe FallenRayne an apology =).
The big benefit is the separation of content (html) and action/behavior (javascript). This is known as Unobtrusive javascript. Keeping these separated makes it easier to change either without affecting the other.
Yes, there has, at least in some portion of the community, not sure how you'd measure it overall.
There are definitely advantages, off the top of my head:
Cleaner / Less code
Easier to debug
Easier to change
Easier to package
Performance
From sheer volume, think of this:
<a onclick="someFunction();">
<a onclick="someFunction();">
<a onclick="someFunction();">
<a onclick="someFunction();">
<a onclick="someFunction();">
Or this once:
$("a").click(someFunction);
You can do this with most frameworks via a css selector, etc, handles many elements at once. This means in server code you're just assigning IDs and classes, the client side is easier to handle separately. It's easier to debug as well, for example: in the console I can do $('a').unbind('click').click(...something new...);
Another benefit is performance. If I can split this into a separate .js file, cached by the client, that's thinner webpages and extra data I'm not sending every time. Smaller web page = faster load.
Here's one more example, thinks about how simple it is, granted some framework action via jQuery going on, but how would this look with inline events?
$("li").hover(function() {
$(this).children().slideToggle();
});
Comparatively, that's a tremendous amount of inline code, even if you leave out the animation portion it's messy (think mouseenter/mouseleave, not mouseover/mouseout...the former, which .hover() uses, is more complicated)
Has there really been a shift away from the old school way of declaring events inline
Yes, definitely, especially with the rise of the JS Frameworks like jQuery, Prototype and so on, all of which encourage declaring events the "new school" way.
and if so, what are the benefits of one of the other?
One of the main reasons is the separation between the HTML structure and the JavaScript programming intelligence (which arguably do belong separated). It makes the markup much, much cleaner and easier to maintain, while all the programming logic is kept in separate files, which has loading performance advantages as well as better maintanability - you have proper libraries that contain the code, instead of fragments of JS code all over the place.
With inline declaration you can assign only one event handler while from code you can assign as many as you wish. Also if you need to assign same event handler to multiple elements doing it with javascript is easier and shorter and you comply to DRY principle.

Tips on optimizing javascript

The things I'm trying to get my website to do are getting fairly complex, some of the things that need to be done take long enough that it gives visible delays.
Mainly, adding content to the document slows things down as well as jquery animations that I'm using.
I create elements using document.createElement("div") rather than just doing document.write("<div id='someId'></div>"), and the animations are the custom animation using .animation();
I'm wondering how I can continue to add content as I am but prevent the browser from freezing every time I want to add something.
Any suggestions for speeding things up so there is less of a delay?
Tips on what to avoid in javascript programming that gives increased delay would be really helpful.
This sounds more like you want to improve the DOM interaction performance rather than javascript, so in that vein:
Yes, document.write is bad, it blocks additional loading (any JS executing before your pages has finished loading basically requires all other processing to stop -- modern browsers like Safari (and by proxy Chrome) and Firefox do a degree of content preloading in order to prevents loads from blocking but subsequent style resolution, etc is largely blocked.
document.createElement is in general the best solution, although their are certain cases where just manipulating innerHTML on an element may be faster -- but that is not yet cross browser compatible (i think innerHTML doesn't exist till Firefox 3.5) and the perform characteristics are tricky.
Reduce the amount of content you load initially -- eg. if you have lots of content (or content that requires large scripts) attempt to delay loading until after the initial page load has completed.
Oh, for animations you should look at CSS animations and they perform much better than any JS implementations, but they're only present in Safari (and by proxy Chrome) and Firefox 3.5 -- definitely not in IE :-(
In terms of JavaScript performance, avoid with and getters/setters like the plague and you should be fine in most modern JS implementations.
I know this is a couple of years late but better late than never considering this question popped up at the top of google's list for javascript animation optimization.
If you need to add a large amount of elements to the DOM and don't want to use innerHTML to do so you can speed that up I believe by adding the elements to a documentFragment first and then injecting the documentFragment all at once into the DOM. I remember reading that DOM injection is the slowest part of using the standard API to create and add elements. documentFragment allows you to inject all of its contents into the DOM in one go eliminating a large amount of overhead caused by calling appendChild or other insertion methods multiple times. appendChild and other insertion methods supposedly don't suffer the same costs when inserting into a documentFragment opposed to inserting into the DOM. I wish I could find the article I read this in as it had some really nice benchmark tests and explanations. I'm sure you can find more information by doing some searches.
As always though which method to use should be determined by testing on a case by case basis. Eventually you'd probably learn which one to use based on structure of the elements, amount, and use.
PS. There may be an issue with styles and documentFragment but I can't remember what was said about them, either way it'd be something worth checking out.
JQuery is great for manipulating the DOM. I'd take a look at their code in order to get some ideas. Or, seeing how I'm way lazy, I'd just use their stuff.
In one of the podcasts Jeff Atwood mentioned you'd have to be crazy to write your own javascript... after using JQuery, I'd have to agree with him.
Although I am a huge fan of jQuery, and it makes development much easier, note that a jQuery statement (or in any JavaScript library) will never be as fast as its semantic equivalent in plain JavaScript because of the extra overhead.
That being said, these are my goto references whenever I want to speed up my JavaScript.
http://home.earthlink.net/~kendrasg/info/js_opt/
http://www.miislita.com/searchito/javascript-optimization.html
There is document fragment function which can make life much more easier. Here is the example use.
function appendDivs(element){
var fragment = document.createDocumentFragment();
for(var i=0;i<10;i++){
var div = document.createElement("div");
fragment.appendChild(div);
}
element.appendChild(fragment);
}
For a complete reference, you can see this post on my blog.
What surprises most people is that using innerHTML is, actually, the fastest way there is to manipulate the DOM.
You can see one benchmark here for example.
// Some functions for easier coding in DOM
function createEl(el){
return document.createElement(el);
}
function addElBody(el){
return document.body.appendChild(el);
}
function addElChild(el, child){ //el- parent
return el.appendChild(child);
}
// Example :
var container=createEl('div');
container.setAttribute('id', 'container');
addElBody(container);
var item=createEl('ul');
item.setAttribute('id', 'list');
addElBody(item);
addElChild(container, item);

Categories