I've been thinking around this question lot of days and i have decided to ask the experts.
How browsers will handle the new import/export syntax ? I mean: will the modules be loaded asynchronously ? Referencing only my main or entry file and browsers will lazy load the requiere modules.
Maybe am i missing or misunderstanding something about this new architecture ?
Thank you very much!
Regards.
This is standardized now and vendors are actively seeking to implement it (for instance, here's the issue for Chromium).
Yes, with two options available; details below.
Not so much "lazy," but yes.
Enabling it (when it's available)
(As far as I know, there is no browser currently shipping with modules support. The is based on the spec linked above.)
To get this behavior (when it's available), you'll specify that your script (even your main one) is a module by using
type="module"
:or for inline scripts
That means that the script will be parsed and handled per the Module definition in the JavaScript specification instead of per the Script definition, which means it can have imports (and exports).
Imports are resolved relative to the script's URL (for modules loaded via a separate resource such as the
main.js
above) or relative to the document (for inline modules like the one above).So for instance, if I have this in my document at
http://farsightsoftware.com/index.html
:...and
nifty.js
contains...then the browser looks for
http://example.com/cdn/thingy.js
, nothttp://farsightsoftware.com/thingy.js
(rather like imports in CSS work).Async
I said above that modules are loaded asynchronously, and there are two options available. This graphic from the spec says it best (see the spec for the latest copy of it):
As you can see, for
type="module"
scripts, if you don't put any special flag attributes on thescript
tag, all of the module's dependencies will be resolved and then the script will be run once parsing of the HTML is complete. If you include theasync
attribute, it may run sooner, before the HTML parsing is complete (for instance, if all the scripts are in cache). (defer
is not valid for modules.)According to this post in Mozilla's website, it's up to the implementation:
This may change in the future, as it is still not fully standardized, but you can be sure that you will not need to add a script tag for every module. Some module loaders today bundle all the files for you, but that's may not be the case when the future will be live, as it will not have an advantage in performance in HTTP2.
You can read the ES6 specification of
import
here.