I am toying around with a pretty intensive ajax based jquery web application. It is getting to a point where I almost loose track of what events that should trigger what actions etc.
I am sort of left with a feeling that my javascript structure is wrong, on a more basic level. How do you guys structure your javascript/jquery code, the event handling etc., any advise for a newbie javascript developer.
Yes, it is possible, and yes, you should (as a JS developer) know what it does and how; but the point of jQuery is to provide a convenient abstraction above that. While jQ is overkill for the first example, it is already perfectly appropriate in the second.
In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.
It is actually best practice to load jQuery at the very end of the body element. This way all of your images load before jQuery.
AMDS!
It's been awhile since first answers got posted to this question and many things have changed. First and foremost, the JS browser world seems to be moving towards AMDs (asynchronous module definition) for code organization.
The way that works is you write ALL your code as AMD modules, e.g.:
define('moduleName', ['dependency1', 'dependency2'], function (dependency1, dependency2) { /*This function will get triggered only after all dependency modules loaded*/ var module = {/*whatever module object, can be any JS variable here really*/}; return module; });
And then modules get loaded using AMD loaders like curl.js or require.js etc, for example:
curl( [ 'myApp/moduleA', 'myApp/moduleB' ], ).then( function success (A, B) { // load myApp here! }, function failure (ex) { alert('myApp didn't load. reason: ' + ex.message); } );
Advantages are:
You only have to include single <script>
element on your page that loads AMD loader itself (some of them are quite tiny).
After that all JS files will be fetched automatically in asynchronous NON BLOCKING! fashion, thus way faster!
Necessary modules will get executed only after its dependencies got loaded.
Modular (which means code that is easier to maintain and re-use).
Global variables pollution can be completely curbed if used correctly.
Honestly, once concept has clicked in your head, you'll never go back to your old ways.
P.S: jQuery does register itself as AMD module starting from version 1.7.
More information on AMDS:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With