How I load javascript?

posted Originally published at aadswebdesign.github.io 1 min read

Intro.

It's based on an old article that I've read a while back about bulletproof loading of webcomponents and written by Chris Go Make Things, someone who knows a lot more about webdesign as me.
The article was about loading loading js in the footer or in the head and using 'async/defer' .

His Approach.

His 'bulletproof' approach was by using document.readyState and DOMContentLoaded in his component classes.

My idea.

It might be bulletproof but complex and hard to maintain The way I do that is Simple, Bulletproof, Fast and hardly needs any maintenance.

How I load js then.

Step 1

First step is to have an index.js within the scripts folder and that contains the following:

//the imports on top. 
(async ()=>{
    /** 
      This is the place where all the js logic ends up but in the right order!
   */
})();

Step 2

Second step, within your index.html this:


<script type='module' src='./path/to/scripts/index.js'> </script>

Explanation

At the first step, the code has been placed in an async (Immediately Invoked Function Expression)! That iife, is the final place where all my js stuff ends up.

This way.

There is no need for using 'DOMContentLoaded' because the promise is 100% fulfilled before it's passed to my index.html. So what I get is a single substance that is complete and ready to use.

Actually, I rarely look at it because there is no need for!

Note!

Placing all js stuff in the right order within you index.js is important! Otherwise, things might give errors because of lacking dependenties.

More about IIFE at MDN(IIFE)

That's it!

If you read this far, tweet to the author to show them you care. Tweet a Thanks

Thanks for the clear explanation, really helpful. Do you ever run into issues with scripts that rely on DOMContentLoaded?

No, because I never use DOMContentLoaded.

There is no need for that!

More Posts

What is Javascript and How It Powers Modern Websites

Sangy K - Aug 12

How I talk with the DOM?

Aad Pouw - Sep 10

Learning Object Destructuring in JavaScript

ypdev19 - Oct 4

JavaScript Objects: Your First Step to Data Magic

Abdelhakim Baalla - Jul 15

The Unchaining: My Personal Journey Graduating from jQuery to Modern JavaScript

kitfu10 - May 20
chevron_left