<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Hasnain's Blog]]></title><description><![CDATA[Hasnain's Blog]]></description><link>https://hasnain.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 01:15:59 GMT</lastBuildDate><atom:link href="https://hasnain.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Burnout]]></title><description><![CDATA[According to Oxford Dictionary, burnout means, "The reduction of a fuel or substance to nothing through use or combustion." The word burnout in workplace usually refers to the same phenomenon where a star player with "I can," or "Give me more," attit...]]></description><link>https://hasnain.dev/burnout</link><guid isPermaLink="true">https://hasnain.dev/burnout</guid><category><![CDATA[work]]></category><category><![CDATA[Developer]]></category><category><![CDATA[mentalhealth]]></category><category><![CDATA[software development]]></category><category><![CDATA[IT]]></category><dc:creator><![CDATA[Muhammad Hasnain]]></dc:creator><pubDate>Fri, 04 Mar 2022 01:38:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/yOzIE5VTEpo/upload/v1646357190179/4BYrwEeFX.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>According to Oxford Dictionary, burnout means, "The reduction of a fuel or substance to nothing through use or combustion." The word burnout in workplace usually refers to the same phenomenon where a star player with "I can," or "Give me more," attitude runs out of fuel to function properly.</p>
<p>The term, "Burnout," isn't really talked about much, hence, "The Naked Emperor." Perhaps because it may carry stigma of being weak, spiritually, mentally or psychologically? Or maybe because the awareness of it will result in demands and changes that the big organizations may not really be a fan of? Capitalism and the robotic middle class. Produce, earn cash, buy this and that, however, that's a whole another topic.</p>
<p>Burnout isn't a unique phenomenon. It has been recognized by many cultures and people, especially Japan where there is a term called, "Karoshi," which means "death by overwork." It is a serious condition that needs to be talked about especially in IT field which in intellectuality and mentally taxing. Why does it happen? What can we do to prevent it? I'll also share my story and some advice at the end.</p>
<p>For whatever reason, a hard working person may feel that either their work isn't important. Might feel under appreciated and feel that they're not adequately rewarded and compensated. It is possible that others may take credit for their work. The environment might have became toxic. Overnights, lack of sleep, running on coffee and lack of meaningful connections etc.</p>
<p>These eventually make a person apathetic. The excitement of learning new things, the joy of small wins, the satisfaction of production something elegant, they all fade away. For such apathy, like any other psychological condition, in order to cope, a person may resort to short term pleasures that keeps them going in the meantime. Short term pleasures might include comfort eating, wasting time on social media, movies, games etc. as all of these stimulate the brain reward circuitry.</p>
<p>This apathy slowly morphs into a crippling psychological state of a total burnout. If you think of work as one of your leg, your family and yourself as the other, standing on one leg day and night will inevitably result in exhaustion to the point where you can't keep up and eventually, fall. There are more things in life that you need to take nurture, like your health, career, goals, ambitions, family, friends, spirituality, physical health among other things.</p>
<p>Burnout does not only affect your psychology but also physiology. The stress that you may experience will literally shrink the brain parts that are associated with memory, reasoning, logic, problem solving, self control and emotional regulation (pre-frontal cortex). Lack of sleep and physical activity also shrinks the brain in an extremely negative manner. The social media or sugary foods one may use as a coping mechanism also overloads your pre-frontal cortex with dopamine which results in further deteriorating of your psychological and physical health. A downward spiral that feeds on itself.</p>
<p>Personally, I learned this the hard way. Committing too much to work and a focus on loyalty, I have realized that I never got to built a specialized skillset nor did any real projects that I could feel proud of, I mean, what should I write on my resume's projects section? I've also at the same time, realized that I've always been underpaid nor have my expertise been used to do something incredible. This makes me sad as I'm a visionary and hardworking, to see I've been left behind compared to my peers gives me no pleasure.</p>
<p>This isn't to bash anyone or anything. It doesn't matter where you work, people pay you to generate them profits, fulfil their vision and help them achieve their goals and that's okay! You can also have a business and you'll also need people to run it too. You need to realize that you are employed purely because you have the skill, no one is running a charity and if for whatever reason you start to underperform, they can easily lay you off and replace you. Be loyal but not to a fault. Help organizations realize their dreams and visions but not at the expense of your own. Work hard but don't trade the "self" for prestige.</p>
]]></content:encoded></item><item><title><![CDATA[Codism: An Open Source Code Playground for Web Developers]]></title><description><![CDATA[Introduction
I've been programming for almost three years and the thing that I find the most fascinating are tools like compilers, transpilers or anything that makes life easy for other developers.
Some time ago, I was discussing compiler constructio...]]></description><link>https://hasnain.dev/codism-an-open-source-code-playground-for-web-developers</link><guid isPermaLink="true">https://hasnain.dev/codism-an-open-source-code-playground-for-web-developers</guid><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[#codenewbies]]></category><category><![CDATA[learn coding]]></category><dc:creator><![CDATA[Muhammad Hasnain]]></dc:creator><pubDate>Thu, 27 Jan 2022 19:10:53 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>I've been programming for almost three years and the thing that I find the most fascinating are tools like compilers, transpilers or anything that makes life easy for other developers.</p>
<p>Some time ago, I was discussing compiler construction with my best friend Waasiq. We talked about tokenizers, parsers, ASTs etc and this got me thinking, how are online tools able to compile HTML, CSS and JavaScript? What about LeetCode and Hackerrank that can compile languages like C++, Java and tens of others?</p>
<p>After thinking about it, I realized that there are simpler ways to get these things done. You don't need to write your own compilers if you want to create something similar to LeetCode and Hackerrank. For some reason, if you do decide to start writing your own compilers, it is going to take you a life time to come up with your own compilers for all the different languages.</p>
<p>We will discuss how LeetCode, Hackerrank and Algoexpert type sites work IE how do they compile the code and run tests on them. Codepen and other such tools may follow similar concepts and the keyword here is "concept." These sites may entail complexities but on a basic level, they are the same.</p>
<h4 id="heading-motivation">Motivation</h4>
<p>This project is purely for educational/learning purposes. I'm not creating this in order to compete with Codepen. I'm just doing this for fun and for my own learning.</p>
<h4 id="heading-journey">Journey</h4>
<p>I'm also going to document all the progress I make on <a target="_blank" href="https://codism.netlify.app/">Codism</a>. So, make sure to follow me here and on <a target="_blank" href="https://www.linkedin.com/in/muhammad-hasnain-5b5484194">Linkedin</a> as well as on <a target="_blank" href="https://dev.to/hasnaindev">Dev</a>. Also join our Discord channel called, <a target="_blank" href="https://discord.gg/SX7QAMBQ">Dev's Hub</a>.</p>
<h1 id="heading-codism">Codism</h1>
<p><a target="_blank" href="https://codism.netlify.app/">Codism</a> is an open source Codepen like tool where you can start writing HTML, CSS and JavaScript. Sometimes you may want to have a quick UI session but creating files and folders is a tedious task and not to forget that it might create a mess when all you wanted to see was how to center a div. For things like these, tools like Codepen can be extremely handy.</p>
<h1 id="heading-how-it-works">How It Works</h1>
<p><a target="_blank" href="https://codism.netlify.app/">Codism</a> takes your markup, styles, scripts and compiles them right inside the browser using a clever "hack". The preview is an isolated <strong>iframe</strong> which is not affected by external CSS or JavaScript and has a completely isolated scope where you may add HTML, CSS and JavaScript using the code editors.</p>
<h4 id="heading-compiling-html">Compiling HTML</h4>
<p>The HTML is directly added to the preview module whenever HTML code editor detect changes. Updating HTML also refreshes JavaScript afterwards in order to ensure that any event listeners that were lost during re-rendering are re-attached. This isn't complex and isn't even compiling by any measures.</p>
<h4 id="heading-compiling-css">Compiling CSS</h4>
<p>The CSS resource is added after it is "compiled." When the CSS code editor detect changes, it takes the CSS as a string and turns it into a blob using the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Blob">Blob web API</a>. At this point the blob/file is inside our memory and we need a reference to it in order to access it. To create a reference, we use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/URL">URL web API</a>.</p>
<p>After that, we create a link tag and assign the URI reference to the CSS blob using the <strong>href</strong> attribute. We must ensure to remove the previous CSS from the preview because if we don't, we'll end up with a memory leak where CSS files keep piling up, not to forget that the styles written previous will persist. When we add the CSS successfully to the preview module, browser automatically handles all the parsing and styling. This is the clever "hack" I referred to.</p>
<h4 id="heading-compiling-js">Compiling JS</h4>
<p>This isn't different from how we load CSS resources. As soon as the JavaScript code editor detect changes, it takes the JS as a string, turns it into a blob using the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Blob">Blob web API</a> and creates a reference to it using <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/URL">URL web API</a>.</p>
<p>Like with CSS, we make sure to remove any previous JavaScript and append the brand new JavaScript to the preview module. We also refresh HTML before adding the new JavaScript. The reason for refreshing HTML is any residual event listeners that were previously applied to the Markup.</p>
<h1 id="heading-roadmap">Roadmap</h1>
<p><a target="_blank" href="https://codism.netlify.app/">Codism</a> will have a lot more features in the future. I'll share what things I'm planning to add to <a target="_blank" href="https://codism.netlify.app/">Codism</a>.</p>
<ol>
<li>Add preprocessors like SASS, LESS, PUG.</li>
<li>Allows users to load CSS and JS libraries and modules using CDNs.</li>
<li>Make the code editor experience robust by adding autocomplete type features.</li>
<li>Ability to sign-up and sign-in.</li>
<li>Ability to save code as projects and share them.</li>
</ol>
<h1 id="heading-collaborate">Collaborate</h1>
<p>Since, this is an open source project, I encourage you to collaborate on it. Pick any features you may like or any bugs you may want to solve and start hacking! Even if you want to improve the README file on Github, that is also something I'd appreciate.</p>
<p>Collaborate at: <a target="_blank" href="https://github.com/hasnaindev/codism">https://github.com/hasnaindev/codism</a></p>
<h1 id="heading-follow-me">Follow Me</h1>
<p>Follow me at: <a target="_blank" href="https://www.linkedin.com/in/muhammad-hasnain-5b5484194">Linkedin</a> and <a target="_blank" href="https://dev.to/hasnaindev">Dev</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Design Pattern: Singleton - Probably the easiest explanation!]]></title><description><![CDATA[Table of Contents

What is Singleton?
Implementation.
When to Use?
An Anti-pattern?

What is Singleton?
Singleton is a design pattern that falls under the category of creational design patterns. Creational design patterns are associated with the simp...]]></description><link>https://hasnain.dev/design-pattern-singleton-probably-the-easiest-explanation</link><guid isPermaLink="true">https://hasnain.dev/design-pattern-singleton-probably-the-easiest-explanation</guid><category><![CDATA[design patterns]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[#codenewbies]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Muhammad Hasnain]]></dc:creator><pubDate>Tue, 17 Aug 2021 10:01:25 GMT</pubDate><content:encoded><![CDATA[<h3 id="table-of-contents">Table of Contents</h3>
<ol>
<li>What is Singleton?</li>
<li>Implementation.</li>
<li>When to Use?</li>
<li>An Anti-pattern?</li>
</ol>
<h1 id="what-is-singleton">What is Singleton?</h1>
<p>Singleton is a design pattern that falls under the category of creational design patterns. Creational design patterns are associated with the simple creation of objects.</p>
<p>Singleton itself ensures that at any given point during the software's runtime, there should be only one instance of an object. Usually, this object is available to the software, globally.</p>
<h1 id="implementation">Implementation</h1>
<p>Before we talk about when to use it, let's quickly implement it and then we can try to understand the nitty-gritty details.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Database</span> </span>{
  <span class="hljs-keyword">private</span> <span class="hljs-built_in">static</span> $instance;

  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Connect to database</span>
  }

  <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get_instance</span>(<span class="hljs-params"></span>): <span class="hljs-title">Database</span> </span>{
    <span class="hljs-keyword">if</span> (is_null(<span class="hljs-built_in">self</span>::instance)) {
      <span class="hljs-built_in">self</span>::instance = <span class="hljs-keyword">new</span> <span class="hljs-built_in">self</span>();
    }

    <span class="hljs-keyword">return</span> <span class="hljs-built_in">self</span>::instance;
  }
}
</code></pre>
<p>If you look at the implementation, you see that the constructor is made private in order to prevent you from creating new instances of the class because database connections in a large system may be expensive.</p>
<p>We use private and static variable <code>instance</code> to store the instance of the Database class.</p>
<p>Using the <code>get_instance</code> static method, we access the instance of the Database class, if in case the instance does not exist, we make sure that it does and then return the instance of the class.</p>
<h1 id="when-to-use">When to Use?</h1>
<p>Use the singleton pattern only when you need an object to have a single instance throughout your software's runtime. From the example above, you can see that a connection to database is usually required only once.</p>
<p>Any other such expensive operations or global configurations should use singleton but beware that singleton is also called, "An Anti-pattern." It should be almost always be avoided.</p>
<h1 id="an-anti-pattern">An Anti-pattern?</h1>
<p>Singleton is one of the patterns that is easy to understand and use. Thus, it may encourage engineers (at least new ones) to overuse it. It should be used only if there is no alternative solution.</p>
<p>Singleton also encourages the use of global variables. For any engineer to keep track of global variables, it increases cognitive load for them. Such cognitive load may lead to poor software. More on cognitive load and psychology later.</p>
<p>Besides, singleton is more or less, a unique instance of a global variable. It can introduce unnecessary restrictions, make unit tests a pain since they may rely on inheritance among other things.</p>
<p>Some call singleton pattern an "evil pattern." Design patterns in general are agreed upon solutions to commonly recurring problems. Systems may use it when there is a good reason to do so, thus knowing this pattern is essential.</p>
]]></content:encoded></item><item><title><![CDATA[How I became a web developer in a year without a degree, a bulletproof method.]]></title><description><![CDATA[Table of Contents

Preface
Need for Clarity
Inverse Goal Setting (The Bulletproof Method)
Consistency + Time

Preface

In life you need either inspiration or desperation. ~ Tony Robbins

Three months into my first semester I had to leave the universi...]]></description><link>https://hasnain.dev/how-i-became-a-web-developer-in-a-year-without-a-degree-a-bulletproof-method</link><guid isPermaLink="true">https://hasnain.dev/how-i-became-a-web-developer-in-a-year-without-a-degree-a-bulletproof-method</guid><category><![CDATA[learning]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Learning Journey]]></category><category><![CDATA[General Advice]]></category><dc:creator><![CDATA[Muhammad Hasnain]]></dc:creator><pubDate>Sat, 31 Jul 2021 20:43:00 GMT</pubDate><content:encoded><![CDATA[<h1 id="table-of-contents">Table of Contents</h1>
<ol>
<li>Preface</li>
<li>Need for Clarity</li>
<li>Inverse Goal Setting (The Bulletproof Method)</li>
<li>Consistency + Time</li>
</ol>
<h2 id="preface">Preface</h2>
<blockquote>
<p>In life you need either inspiration or desperation. ~ Tony Robbins</p>
</blockquote>
<p>Three months into my first semester I had to leave the university as it was clear we couldn't afford it. My father lost his business and we essentially became poor. With no education and a degree, I was rejected from a ton of places. I am a good teacher, I am really good with computers but non of that mattered.</p>
<p>In Pakistan, parents pay for their children's education until they get a degree. You cannot earn enough without a degree or get student loans either. Without any degree your chances of having a good and respectable job or a status in society are pretty low.</p>
<p>Looking at my peers, getting rejected and even being kicked out of an internship hurt me and made me angry too. It was a really tough time in my life where I lost, not only the chance to get a good education but friends too and I became extremely depressed.</p>
<p>I had made a decision nevertheless and I committed to it. I used all my "negative emotions" to drive me towards my goals. "Revenge" aside, in the end, it is all about having a better life not only for yourself but for your family too.</p>
<p>I did became a web developer and now I have one year and eight months of total experience. I do not possess any degree and or certifications.</p>
<p>Today, I'm going to share with you how I became a web developer in a year without any degree. What I'm about to share does not only applies to this field but to all other engineering and technical fields. Usually, in these fields employees require you to have a certain set of technical skills and these skills are measurable, both quantitively and qualitatively.</p>
<h2 id="clarity">Clarity</h2>
<blockquote>
<p>The best time to have a map is before you enter the woods. ~ Brendon Burchard</p>
</blockquote>
<p>Clarity is perhaps one of the most important thing you can have in your life. When you are clear about what is it that you exactly want, you have an edge over other people. You can divert all of your attention and energy towards the attainment of that goal.</p>
<p>Remember, this concept of clarity that we're talking about will not only make you a web developer but also a better person. This is an invitation to you to lead a life that has been examined rather than the one that is reactive and lived according to what other people expect of you.</p>
<p>Be precisely clear on what you want because a lot of people climb the proverbial ladder of success, only to realize that it was leaning against the wrong wall.</p>
<h2 id="inverse-goal-setting-the-bulletproof-method">Inverse Goal Setting (The Bulletproof Method)</h2>
<p>Do you want to become a web developer? Let's suppose you want to become a front-end developer. What you need to do is to google this term, "front-end jobs" and you will get a list of front-end jobs, easy as that.</p>
<p>What you need to do after that is to click on the job posts and look at the skills they're expecting from their candidates. Usually they'll contain things like HTML, CSS, JavaScript, SASS, ReactJS/VueJS/AngularJS. Write these skills down.</p>
<p>Go through as many posts as you can and write all the skills they require. Some of them may contain something unique and different, like a project management tool or a certain library. You may write those down too without any worry.</p>
<p>After that what you would need to do is to look for a pattern. What set of skills do you see being repeated in almost all of the job posts? For us, these skills should be repeated, "HTML, CSS, JavaScript, SASS and ReactJS." You may ignore things like RxJS, Bugherd or other such tools and libraries which are just mentioned a handful of times.</p>
<p>At this point, you should've figured out the pattern. The tools and languages that are essential for you to learn in order to land that specific job.</p>
<p>What we just did is what I call, "Inverse Goal Setting." I was thinking of a clever name but honestly, this is much better than "Inverse Back Tracking." I'm cringing really hard right now, haha.</p>
<p>Anyways, now that you know what skills you need, you can start your research on what to learn first and what comes latter. You make a map of sorts. In our example, we want to become a front-end developer. I would start with HTML and CSS and learn them before heading into SASS which is an intermediate concept. I will start with JavaScript before I head into TypeScript, Angular or React which are advanced tools and libraries.</p>
<p>As soon as you're done with that, you need to start taking action! Udemy, YouTube, e-books, FreeCodeCamp all of these platforms contain all the knowledge you need to become a front-end or back-end developer.</p>
<p>Study, make lots and lots of projects on your own. Sure, there are a lot of code-along project videos that you can watch and code along with but you also need to create something on your own. You need to take the concepts and apply them as you understand them, it will help you learn more than anything else.</p>
<p>After you learn most of the things that were on your list and you have projects online and your code is on Github, you are pretty much ready to start applying for jobs. Since, this isn't an interview advice post, I am not going to discuss data structures, algorithms, clean code etc.</p>
<h2 id="consistency-time">Consistency + Time</h2>
<p>Consistency is the key to mastery! If you want to become good at something, you need to spent large chunks of your time doing that thing on a daily basis, even when no one is looking and especially when no one is looking!</p>
<p>Ronaldo used to wear weights on his ankles and kick football for hours. Elon Musk used to work 120 hours in a single week and no wonder he is running multiple companies. There are tons of other such success examples.</p>
<blockquote>
<p>It is in the moments of decisions that our destiny is shaped. ~ Tony Robbins</p>
</blockquote>
<p>All such success stories have similar patterns, certain habits that they all had. They decided what they wanted, they trained and worked for hundreds of hours every single week or month for years. They trained when no one was looking, they trained when they felt like giving up and became depressed.</p>
<p>I had similar experience too. Studying for 12+ hours each day there were days when I completely burnt up and when I became depressed and really uncertain at times and questioned myself but I had made my mind and I was going to do it. It may become extremely hard at times but you keep at it anyway.</p>
<p>It is your decision to work hard on a daily basis that separates you from the crowd. In the end, the crowd will notice your success and cheer you on, they always do. Your critics becomes your supporters, but they will never see how hard you worked and that is okay because I think we're all like that unless we choose to gain awareness of self and choose to look closely and study successful people.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Know what you want! If you want to be a front-end developer or back-end developer, android developer or a game developer. Checkout job posts for that specific title and note down all the skills, tools and libraries they want from their desired candidate. Figure out what set of skills, tools and libraries are being repeated, viola, you now have a pattern. Make a sensible plan and get to work! Work hard, be consistent and be patient.</p>
<p>UPDATE: I'm really grateful to you all and very glad that this post served as an inspiration to many. This is my <a target="_blank" href="https://www.linkedin.com/in/muhammad-hasnain-5b5484194/">Linkedin</a> profile if you guys want to connect. Have a great day!</p>
]]></content:encoded></item><item><title><![CDATA[Dynamic Module Pattern for JavaScript]]></title><description><![CDATA[Note: Please make sure that you are already aware of the code-splitting and dynamic import mechanism. This pattern is module bundler agonistic as long as it provides code splitting and dynamic import features. With some work, you can have own impleme...]]></description><link>https://hasnain.dev/dynamic-module-pattern-for-javascript</link><guid isPermaLink="true">https://hasnain.dev/dynamic-module-pattern-for-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[optimization]]></category><category><![CDATA[performance]]></category><category><![CDATA[patterns]]></category><category><![CDATA[design patterns]]></category><dc:creator><![CDATA[Muhammad Hasnain]]></dc:creator><pubDate>Tue, 27 Jul 2021 22:41:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1627421942648/P1pmlGCTa.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Note:</strong> Please make sure that you are already aware of the code-splitting and dynamic import mechanism. This pattern is module bundler agonistic as long as it provides code splitting and dynamic import features. With some work, you can have own implementation of this pattern.</p>
<p>Users often leave a website in about 10 to 20 seconds as soon as they visit it. Slow websites increases bounce rate. If a website is slow and have a high bounce rate, it will inevitably drop the website ranking. Besides, even if it maintains good score, users will have no choice but to leave the website after a few seconds.</p>
<p>If performance of a website is an utmost priority, we may implement lazy loading of images, use picture elements, use caching, CDN, among tons of other optimization techniques. However, the problem that I noticed was that people were struggling with loading JavaScript on demand.</p>
<p>Hand-picking JavaScript libraries has its own problems. For instance, we might need to include different script tags for each page that makes use of certain markup or library. This can lead to clutter and maintenance issues. Some may have an arbitrary implementations that may or may not work under certain conditions. Even Google Tag Manager can be cumbersome.</p>
<p>In order to solve this problem, I introduce...</p>
<h1 id="the-dynamic-module-pattern">The Dynamic Module Pattern</h1>
<p>The Dynamic Module Pattern is a pattern where you define, right in your markup, what associated JavaScript modules should be loaded. Suppose, you have a slider module in your app that makes use of the library called, <a target="_blank" href="https://flickity.metafizzy.co/">flickity.js</a>. When you include the markup, the <em>dynamic module pattern</em> will load appropriate JavaScript bundles for it and if you completely remove the slider, no JavaScript will be loaded. You don't have to worry about manually removing it.</p>
<p>This not only takes away the headache of micromanaging libraries in your markup using script tags or a list of <em>if</em> statements in case you are using a templating engine. Another great thing about this pattern is that you don't really need to worry about where the markup is coming from as long as certain attributes are defined (See explanation section on more benefits).</p>
<p>For instance, it could be a Shopify <em>snippet</em> or <em>section</em>. A WordPress <em>post</em> or <em>shortcode</em>, Laravel or Node based server-side sites using templates, static sites, this pattern also work perfectly with all of them. Unless of course, your development environment already provides a code-splitting mechanism like <em>create-react-app</em> or <em>vue-cli</em>, in which case you don't really have to worry about this.</p>
<h2 id="how-does-it-work">How Does it Work?</h2>
<p>I'll provide the code snippets and after that I'll explain what's going on. I'm using this pattern for a WordPress theme that uses WebPack and Svelte. The same can be done for React or Vue especially if you are making isolated snippets or widgets. The Shortcode provides user the ability to give it a module name and the associated JavaScript bundle will be loaded for it. Magic! 🎩</p>
<h3 id="markup">Markup</h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">data-module</span>=<span class="hljs-string">"slider"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h3 id="javascript">JavaScript</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> modules = <span class="hljs-built_in">Array</span>.from(<span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'[data-module]'</span>));

modules.forEach(<span class="hljs-function">(<span class="hljs-params"><span class="hljs-built_in">module</span></span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> componentName = <span class="hljs-built_in">module</span>.getAttribute(<span class="hljs-string">'data-module'</span>);

  <span class="hljs-keyword">import</span>(<span class="hljs-string">`./components/<span class="hljs-subst">${componentName}</span>.svelte`</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">component</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (component &amp;&amp; component.default) {
        <span class="hljs-keyword">new</span> component.default({
          <span class="hljs-attr">target</span>: <span class="hljs-built_in">module</span>,
        });

        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${componentName}</span>.svelte loaded.`</span>);
      }
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.warn(<span class="hljs-string">`<span class="hljs-subst">${componentName}</span>.svelte failed to load.`</span>, error);
    });
});
</code></pre>
<h3 id="explanation">Explanation</h3>
<p>The HTML is quite simple. We define a simple HTML <em>div</em> element with the attribute of <em>data-module</em> which is also the name of the <em>component</em> aka <em>file</em> that we need to import in order to bring this component to life. This element is simply the <em><a target="_blank" href="https://svelte.dev/docs#Client-side_component_API">root</a></em> element for svelte slider component.</p>
<p>The JavaScript is however, interesting. It first fetches all the elements present in DOM that have the <em>data-module</em> attribute defined. It loops through all those elements and for each single one, it gets the <em>data-module</em> attribute.</p>
<p>After that, it tries to dynamically import a certain <em>component</em> that exists in the components folder (<strong>./components/{component-name}.extension</strong>). If the component is successfully loaded, we're notified instantly. If the component is not present or fails to load, we receive a warning.</p>
<p>The best thing about this pattern is that I can add and remove this markup or I can use it multiple times in my page. This pattern will make sure that the appropriate JavaScript is loaded or not loaded.</p>
<p>Does this load JavaScript bundles multiple times if I make use of the <em>data-module</em> several times in the page markup? Please, keep reading. I'll answer that soon!</p>
<h2 id="without-module-bundlers">Without Module Bundlers?</h2>
<p>You can definitely modify this pattern to fit your needs. For instance, you can use intersection observers and or events like key events, mouse events, hover, scroll and what not to dynamically load JavaScript. Imagine, you can prefetch or pre-connect components on user events and fetch them whenever they are needed. 🚀</p>
<p>Like I said, you can use this pattern without module bundlers. You can implement the <em>Dynamic Module Pattern</em> using a custom import statement that can load JavaScript from CDN or locally from your own website. However, keep in mind that this may not be as easy as you think. There are several problems that you need to keep in mind.</p>
<h2 id="caveats-with-custom-implementations">Caveats With Custom Implementations</h2>
<p><strong>Repeated <em>data-module</em> Elements:</strong> If an element repeated more than once, a naïve implementation will dynamically load script tags for each individual element. For instance, if an element is used in four places that makes use of bundles that weight about 80 KBs, you've just downloaded 320 KBs of JavaScript!</p>
<p><strong>Dependencies:</strong> This is a major issue with custom implementations. Module bundlers can easily nest or map out the dependency tree but in custom implementation, any bundle that is imported must be and need to be available at a global scope, unless they are isolated containers that one does not really need to worry about.</p>
<p>This also begs the question of, "What if I need to load <a target="_blank" href="https://flickity.metafizzy.co/">flickity.js</a> and then my custom JavaScript in order to make my slider functional?" This is an actual issue. You'd have to handle the dependency tree on your own which is not a simple task IMO.</p>
<h2 id="caveat-with-original-implementations">Caveat With Original Implementations</h2>
<p><strong>Parallel Scripts Loading:</strong> This pattern can be definitely tweaked in order to support parallel script loading. Right now, my method does not support that. For instance, you can load <em>Vue</em> along with your custom JavaScript bundle for which <em>Vue</em> is a dependency. As soon as they are both loaded, you appropriately initialize them by passing <em>Vue</em> as a parameter.</p>
<h2 id="bonus-naive-custom-implementation">Bonus: Naïve Custom Implementation</h2>
<p>This is just for fun in case you want to test things about without the headache of setting up a module bundler!</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> customImport = <span class="hljs-function">(<span class="hljs-params">src</span>) =&gt;</span>
  <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> script = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'script'</span>);
    script.async = <span class="hljs-literal">true</span>;
    script.onload = resolve;
    script.onerror = reject;
    <span class="hljs-built_in">document</span>.body.appendChild(script);
  });

<span class="hljs-keyword">const</span> modules = <span class="hljs-built_in">Array</span>.from(<span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'[data-module]'</span>));

modules.forEach(<span class="hljs-function">(<span class="hljs-params"><span class="hljs-built_in">module</span></span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> componentName = <span class="hljs-built_in">module</span>.getAttribute(<span class="hljs-string">'data-module'</span>);

  <span class="hljs-comment">// This could be anything, CDN or a local asset.</span>
  customImport(<span class="hljs-string">`<span class="hljs-subst">${componentName}</span>.extension`</span>)
    .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-comment">// script context IE window.Vue etc</span>
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.warn(<span class="hljs-string">'failure'</span>, error));
});
</code></pre>
<p>Let me know if you found <em>Dynamic Module Pattern</em> helpful. Please, do share your thoughts on this, I would love to hear how this might help you. Please, make sure to react and share this too. Thank you for reading!</p>
<p><em>Cover image credits: <strong>Anthony Shkraba</strong> from <strong>Pexels</strong></em></p>
]]></content:encoded></item></channel></rss>