I have a serious project with big JS file with many functions, and now I have some questions about it.
Of course, I will stick together all my js files and gzip it, but I have a question about functions initialisations. Now I have many, many simple functions, without any classes. I heard that it is better to separate my code into many classes, and I want to do it, and on page generation step mark in my script, which classes I need on specific page. For example, I don't need a WYSIWYG editor at the main page, and so forth, so I will create special var with array of js classes which I need. Is this the best practice? Will clients get performance and memory savings?
开发者_JS百科
Suppose that I have many links with onclick actions. What is better: leave them as
<a href="#" onclick="return smth();">
or rewrite as<a href="javascript:void(0);">
and create jquery .bind in document.ready section? But what if the client wants to click something before the document is ready?After a click on something I must create a div with specific static html. Where is it better to store this content? In some var in my class? Or maybe in some template?
I usually organize my JavaScript using namespacing to prevent function name clashing and further add each object into it's own .js file for organization purposes
var MyObject = function() {
return {
method_1 : function() {
// do stuff here
},
method_2 : function() {
// do stuff here
}
};
}();
MyObject.method_1();
MyObject.method_2();
I then import whatever is needed on my pages. Having a few extra global functions that aren't used on a page won't make a noticeable change in performance.
Some people turn the whole onclick in HTML into a grand philosophical debate... for me, it's dirty, yet easy to read and quick to implement. Binding events works great and completely separates JavaScript from HTML but sometimes can be difficult to maintain if your HTML being maintained by many developers gets very sloppy
Keeping the HTML bits in JavaScript has worked fine for me
You might also be interested in looking at the Google Closure JavaScript compiler.
Also: If your JS is large enough to affect performance, you may actually end up getting better performance out of separate files and load depending on what your page initially needs or load-on-demand (via jQuery getScript).
You might also want to look into what kinds of actions you expect users to be using before the DOM is ready.
As for HTML in JS (or vice-versa). It depends. How much HTML are you building? I usually don't put more than one line of HTML in a .html() statement. If it's really more than that, I look at a different solution (like pulling it from another source on-demand or putting it somewhere, hidden, in the page and yanking it over).
精彩评论