Intro.
This is a follow up of my previous article How I load my js
.
What I use as an example here are three simple webcomponents for my articles, extensions of the HTMLDivElement and they are called (<article-header>,<article-main> and <article-footer>).
The aim of it is to make my articles more easy maintainable. Also,it is about of how I load them and not of how they are created.
How I do it?
- Step 1
Somewhere in my folder structure I have a folder called webComponents
, within that I have a folder that contains the web components and a js file called components_export.js
and contains three exports like this:
export {articleHeaderDefine} from './path_to/article_header.js';
- Step 2
Within my index.js I have this:
import * as WCP from './../path/to/components_export.js';
(async()=>{
//note; in this case order doesn't matter but they should be invoked before anything else (on top)!
await WCP.articleHeaderDefine();
await WCP.articleMainDefine();
await WCP.articleFooterDefine();
})();
Explanation.
And as stated in my previous article!
The components are part of my iife and this is a fullfilled promise before it enters the index.html. As a result of that, they are available in any order and at any time.
At last.
For who this is?
Those who are new to Javascript and want to learn more about it or just want to improve their skills as I constantly do too.
Some links here for more info.
More about IIFE at MDN(IIFE)
More about Javascript Modules at MDN(JS Modules)
Top comments (4)
You could improve loading time by not using one await after another but by using await Promise.all(). This way they would all execute concurrently.
Before:
After:
Thanks a lot for this.
I will work on that.
Of course i don't know the rest of your code but another thing i noticed is that with the current implementation (the async IIFE) you can't control that code only executes when those functions have finished. To fix this you could use the promises then, catch and finally functionality. This way you don't need an IIFE and you can ensure that code only runs when they have finished executing.
Before:
After:
The 'iife' here I will keep because this the final file where I collect other things too and what is going to my index.html