Created
September 25, 2010 19:18
-
-
Save robotlolita/597176 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// --[ main.js ]--------------------------------------------------------------- | |
require('A.js', function cba() { /* A.js was loaded */ }); | |
// --[ A.js ]------------------------------------------------------------------ | |
require('B.js', function cbb() { /* B.js was loaded */ }); | |
// --[ B.js ]------------------------------------------------------------------ | |
/* dummy file */ | |
// ---------------------------------------------------------------------------- | |
/* | |
Now, when you require A.js, the function gets a callback to fire when A.js was | |
fully loaded, right? Now, instead of sticking this callback directly in the | |
`onload` event, you wrap the function inside another function. | |
function() { | |
if (no_more_dependencies) { | |
origiinal_load_callback(); | |
} | |
} | |
This functions checks if the current script has any dependencies, and if not, | |
calls the actual callback. These dependencies could be handled like: Every | |
time a new `require` function is called, the modules to load are appended to | |
the dependency list, and when they are loaded (onload event) that module is | |
removed from the dependency list. | |
Which gives basically the following: | |
- dependency_list = [] | |
- require('A.js'); | |
- dependency_list = ['A.js'] | |
- A.js is loaded and begins to execute | |
- require('B.js') | |
- dependency_list = ['A.js', 'B.js'] | |
- A.js finishes executing | |
- dependency_list = ['B.js'] | |
- B.js is loaded and begins to execute | |
- Since there are no other require calls, it just executes the `onload`, which | |
is attached to A.js's require call. It also removes `B.js` from the | |
dependency list. | |
- A.js `onload` is executed, checks if there are anything in the dependency | |
list, and since there isn't, calls the A.js callback (cbb). | |
- Now, A.js callback is linked to main.js' require call. This callback also | |
checks if there are any dependencies in the list before calling the actual | |
callback (cba). | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment