What does synchronous vs asynchronous loading mean? - javascript

Reading from this site, I understand that using commonjs means that when the browser finishes downloading your files, it will have to load them up 1 by 1 as they depend on each other. But with AMD, it can load multiple ones at the same time so that even if file a depends on file b, it part of file a can be executed before file b is finished?
CommonJS Modules: The dominant implementation of this standard is in
Node.js (Node.js modules have a few features that go beyond CommonJS).
Characteristics: Compact syntax Designed for synchronous loading and
servers
Asynchronous Module Definition (AMD): The most popular
implementation of this standard is RequireJS. Characteristics:
Slightly more complicated syntax, enabling AMD to work without eval()
(or a compilation step) Designed for asynchronous loading and browsers

Synchronous programming is executing code line by line. Same with loading.
It will load 1 by 1 whatever that you are loading.
Real world example: You are in a queue in cinema for a movie ticket.
Asynchronous would be many people in restaurant. You order food and other people order food. They dont need to wait for your order to finish.
Everyone can order but you dont know when the order will come. Same as with loading. You can load multiple things at the same time or different intervals but it doesnt guarantee that it will come in that order.
I hope the explanation is good enough.

The syntax with CommonJS in loading modules is as such:
var MyModule = require("MyModule");
As you can see, this will block the thread until the module is downloaded, from either your filesystem or the web. This is called synchronous loading. This is impossible to achieve in a normal web browser environment without affecting user experience, since we cannot block the thread as the browser uses the thread to update the graphics.
With RequireJS, it's done as such:
// In your module
define(["dependencies", ...], function(){
return MyModule;
})
// In your web page
require(["dependencies", ...], function(MyModules, ...){
// do stuff here
});
With this model, our web page does not depend on the timing of when the module should be loaded. We can load our scripts in parallel while the page is still being loaded. This is called asynchronous loading. Once the scripts are loaded, they will call define which notifies RequireJS that the scripts are indeed loaded and executed. RequireJS will then call your main function and pass in the initialized modules.

Related

How do I calculate the load time penalty for Node.js package?

To give some context, I'm interested in learning how to optimise the cold start time of a Node.js Express application running onboard a Google Cloud Function.
So far, I've learned the biggest penalty for cold boots is the loading of dependencies using require statements. As an software engineer a scientific mind tells me it will be based on number of files, size of files, number of dependencies, caching. However, perhaps optimising is more of an art than science so any pointers or feedback from your own experience is most appreciated.
My questions are
If I surround a const x = require('x') with two process.hrtime() statements and measure the time difference, will I be measuring the load time for the entire package load time of 'x'?
If so, does this include the loading of all files within this package? How about the dependencies this package requires- when are they loaded (which leads to my third question 3).
If a require statement is inside a conditional block e.g. if (condition) { const x = require('x'); }, at what point is it 'loaded' and what does 'loaded' really mean (i.e. in memory, parsed, executed etc)? Will it 'load' at the moment in runtime the statement is reached (or not), or will the require happen regardless when the program begins execution?
Yes, require is just a normal function which either returns the module if it's in memory or loads it if it isn't, which means reading the file, parsing it and executing it (and of course it may involve requiring other dependances).
There's no problem benchmarking it (just make sure you measure the first require of a file, as the module is cached).
If a require is in your file but isn't executed (for example because it's behind an if statement), it won't have any more effect than if it weren't in your file. And the loading won't happen before the statement is reached.

How does Node.js load scripts into memory?

In the browser, the DOM is parsed and scripts are loaded and parsed in the order they are defined.
In Node.js, how are scripts loaded into memory?
Is the entire graph of scripts defined by the require statements in each file traversed at initialisation-time, with the resulting objects and values hydrating the stack and heap ready for execution to start?
Synchronously. Whenever it encounters a require it synchronously loads the script and runs it - then, when other scripts are found it synchronously loads them.
IIRC in the 0.2 days there was an asynchronous version but it's not here for a long time. As for what it actually does:
Basically, what it does is a fs.readFileSync.
More specifically - Calling require calls _load which in turn first checks the cache and then it creates the module and it calls the relevant extension. Since multiple extensions are allowed (for example .json) it loads each one differently, in the .js case which is the common case it just calls fs.readFileSync and then compiles it (which involves wrapping it, injecting exports and running it).

Asynchronous loading JavaScript functions.

I am building a framework in which I have merged all JavaScript files into one file (minify).
Example:
function A() {} function B() {}
Through minified file i want to load function asynchronous and remove from HTML when its work is done.
Example: load function A when it is required but not function B.
I have seen one framework Require.js but in that it loads JavaScript file asynchronous based on requirement.
Is there any framework which loads JavaScript functions on demand which are defined in same js file.
The downside to concatenation is you get less fine-grained control over what you are including on a given page load. The solution to this is, rather than creating one concatenated file, create layers of functionality that can be included a little more modularly. Thus you don't need all your JS on a page that may only use a few specific functions. This can actually be a win in speed as well, since having just one JS file might not take advantage of the browsers 6 concurrent connections. Moreover, once SPDY is fully adopted, one large file will actually be less performant than more smaller ones (since connections can be reused). Minification will still be important, however.
All that said, it seems you are asking for something a little difficult to pull off. When a browser loads a script, it gets parsed and executed immediately. You can't load the file then... only load part of the file. By concatenating, you are restricting yourself to that large payload.
It is possible to delay execution by wrapping a script in a block comment, then accessing it from the script node and eval()ing it... but that doesn't seem like what you are asking. It can be a useful strategy, though, if you want to preload modules without locking the UI.
That's not how javascript works. When the function's source file is loaded, the function is available in memory. Since the language is interpreted, the functions that are defined would be loaded as soon as the source file was read by the browser.
Your best bet is to use Require.js or something similar if you want to have explicit dependency chains.

Dojo require with single argument synchronous?

My company is moving from classic Dojo syntax to AMD. We have a few situations where we need to dynamically load modules synchronously.
Require in dojo doesn't seem to officially support synchronous loading (at least it's not documented anywhere) but it seems to work if you don't pass in the a function as the second argument (in 1.7.2 at least).
require(["path/to/my/Module"]);
I've added extra latency in Fiddler and it's definitely loading before moving onto the next line.
Does anyone know if this is safe to rely upon? I don't particularly want to litter the codebase with this if it's just a hangover from the classic style that'll be retired in 2.0.
AMD does not support synchronous loading even when using commonJs style requires. The require function will only load synchronously if the module has already been loaded. See:
AMD API: https://github.com/amdjs/amdjs-api/wiki/require#requirestring
See also: require.js synchronous
If you have already loaded the module asynchronously then it is possible to use commonJs style requires, eg:
var lang = require("dojo/_base/lang");
However, if you have not already loaded it, it will throw an undefinedModule error (I've testet this in v1.9). If this works in v1.7 then this has been fixed in later editions of Dojo.
It is not possible to temporarily put it into synchronous mode either by passing a new config to Dojo, eg:
require({"async":false});
The async setting can only be set at load time (see: http://dojotoolkit.org/reference-guide/1.9/loader/amd.html#loader-amd-configuration). Hence, you select either asynchronous or synchronous at the initial load and then you are stuck there.
I would advise refactoring any code that requires synchronous operation. This is usually possible and the result will be probably be better and quicker code.

displaying progress bar for labjs, labjs callbacks

How can I keep track of what scripts have been loaded so far so I can display a progress bar when using labjs (http://labjs.com/)? wait() doesn't work because then it won't parallel load the next resource. Basically i'm looking for some kind of non-blocking callback function i can tie into. Does this exists in labjs?
wait() does not affect the parallel loading of LABjs... it will always parallel load as much as possible (allowed by the browser). wait() only affects the execution of scripts. If it's inserted between two script() calls, it ensures that the second script will "wait" for the first script to finish executing before it executes.
No, there is no exposed API for the load-finishing on scripts, because browsers do not expose a consistent API for when a script finishes loading (only when it executes: "onload", as confusing as that name is).
Now, you can do a progress meter using wait() calls in between each script, but it will tell you something slightly different than what you asked: what percentage of the scripts have executed, not what percentage of the scripts have downloaded. Depending on your needs, that might be quite acceptable.

Categories

Resources