<?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" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[My Thoughts]]></title><description><![CDATA[Thoughts, stories and ideas.]]></description><link>http://blog.andrewbeng89.me/</link><image><url>http://blog.andrewbeng89.me/favicon.png</url><title>My Thoughts</title><link>http://blog.andrewbeng89.me/</link></image><generator>Ghost 2.18</generator><lastBuildDate>Fri, 01 May 2026 17:05:08 GMT</lastBuildDate><atom:link href="http://blog.andrewbeng89.me/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Vue.js London 2019: Towards Scalable Apps]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>The Vue.js London conference returned this year albeit at a bigger and grander venue, the O2 Arena. The conference organisers had positioned the theme of this year's edition to herald the long-anticipated release of features and tools in Vue 3.0. The series of talks covered an array of</p>]]></description><link>http://blog.andrewbeng89.me/vue-js-london-2019-towards-scalable-apps/</link><guid isPermaLink="false">5df7201e5b9cf12e6fdee1cf</guid><dc:creator><![CDATA[Andrew Beng]]></dc:creator><pubDate>Mon, 16 Dec 2019 06:28:13 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1524177706764-8dd0704f2520?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=1080&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="https://images.unsplash.com/photo-1524177706764-8dd0704f2520?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="Vue.js London 2019: Towards Scalable Apps"><p>The Vue.js London conference returned this year albeit at a bigger and grander venue, the O2 Arena. The conference organisers had positioned the theme of this year's edition to herald the long-anticipated release of features and tools in Vue 3.0. The series of talks covered an array of current best-practice topics in the morning sessions, while Vue 3.0 features and updates (in particular the Composition API) were squarely in the spotlight after lunch.</p>
<p>Here are some of the highlights from Vue.js London 2019!</p>
<h3 id="vuespointofviewopinionatedapproachesinvuejsprojects">Vue's point of view - opinionated approaches in Vue.js projects</h3>
<p>Vue.js London 2019 opened with a series of three talks on topics often associated with &quot;polish and optimisation&quot; in intermediate to advanced Vue.js projects. Vue Mastery's slick presentation work clearly communicated in <a href="https://github.com/atomjar">Adam Jahr</a>'s talk on the <a href="https://www.vuemastery.com/courses/animating-vue/transitions/">UX benefits of using animations</a> in a front-end interface to direct users' focus. Vue's built-in transition and transition-group components make creating organic and reusable CSS transitions a breeze when compared to a vanilla CSS implementation.</p>
<p>The <a href="https://slides.com/mayashavin/styling-with-vue/fullscreen#/">contentious topic of CSS-in-JS</a> was the second topic of the day as <a href="https://github.com/mayashavin">Maya Shavin</a> led the audience through a Brief History of Front-end development for the web. Developers using Vue.js out-of-the-box are offered the option of encapsulating component styles with Scoped CSS. CSS Modules is another common approach (especially in the React world) to scope CSS classes locally with the added ability to compose classes. The second alternative to Scoped CSS is styled-components, presented by Shavin as the only &quot;true&quot; CSS-in-JS option allowing for encapsulation, extensibility and theming. However, strong caveats against styled-components were added concerning dynamically in-lined classes on runtime (without the possibility of caching), and potential security issues due to string template interpolations if users are allowed to input styles.</p>
<p><a href="https://github.com/filrak">Filip Rakowski</a> followed on with a practical live demo of some <a href="https://vueschool.io/articles/vuejs-tutorials/faster-web-applications-with-vue-3/">easy-to-do Webpack optimization</a> drastically reducing initial-load times in production apps with the help of dynamic imports and pre-fetching.</p>
<p>As an interesting side note to these presentations, all the topics had previously been discussed in Factorial's front-end working group meetings.</p>
<h3 id="itsallaboutthedom">It's all about the DOM</h3>
<p>With data visualisation an ever useful front-end development tool-in-the-box to have, the next talk dived into the world of SVGs, interactive charts, and D3.js. <a href="https://github.com/CodesOfRa">Ramona Biscoveanu</a> highlighted some key considerations to keep in mind when <a href="https://slides.com/codesofra/data-visualization-in-2#/">integrating Vue.js in D3.js</a> based data visualisations. Firstly, although both libraries are centred around data driven DOM manipulation, the Vue.js renderer is virtual DOM based while D3.js renders SVGs by selector-based manipulation of the DOM. Vue's virtual DOM and templating layer in turn allow developers to create SVG based charts in a more intuitive and declarative manner. Secondly, Vue.js offers a first-class reactivity layer compared to D3.js (which is intrinsically not reactive). Finally, a key (if not the main) benefit of using D3.js is the rich set of visual and geospatial analytics layouts, projections and helper methods which would be impractical to write from scratch.</p>
<h3 id="gettingtotherouteofthings">Getting to the route of things</h3>
<p>As a segue into more Vue 3.0 centred topics after lunch, the morning talks concluded with an update from <a href="https://github.com/posva">Eduardo San Martin Morote</a>'s update on improvements coming soon to the Vue Router. Rather than brand-new features, updates to the Router focused on addressing current shortcomings and limitations in the current version, and features aligned with Vue 3.0. Vue developers can expect: out-of-the-box TypeScript support, scoped slots for the router-link component, improved navigation failure handling, (finally) <a href="https://paths.esm.dev">path ranking</a>, truly dynamic routing, and support for Vue 3.0's Composition API.</p>
<h3 id="thepathtovue30">The Path to Vue 3.0</h3>
<p>The afternoon sessions kicked off with a couple of talks by <a href="https://github.com/gregg">Greg Pollack</a> and <a href="https://github.com/LinusBorg">Thorsten Lünborg</a> about the new Composition API. In a similar vein to Vue Mastery's <a href="https://www.vuemastery.com/vue-3-cheat-sheet/">Vue 3 Cheat Sheet</a> (also released during Vue.js London), Greg outlined the main shortcomings of current code sharing techniques, while highlighting the <a href="https://www.youtube.com/watch?v=6HUjDKVn0e0">key benefits and reasons</a> for adopting the new API. Thorsten complemented introduction with more concrete <a href="https://github.com/LinusBorg/composition-api-demos">use cases and implications</a> on production scale apps.</p>
<p>As experienced in large projects undertaken at Factorial, Vue components can quickly grow into unwieldy monoliths which are hard to reason about, and harder to maintain or even refactor. Larger apps also tend to feature recurring fragments of business logic as code which is often copy-and-pasted due to Vue's options based syntax.</p>
<p>A typical approach to sharing logic across components is the use of mixins, which in turn introduces the problem of naming conflicts and non-explicit traceability of methods and properties. The new <a href="https://vue-composition-api-rfc.netlify.com/#summary">Composition API</a> enables business logic to be abstracted into reusable Composition Functions, which are as easily understood and used as utility functions. Granted that some concepts of the Composition API are completely new and non-trivial (e.g. the difference between <code>reactive</code> and <code>ref</code> and using <code>toRef</code>), it is a learning curve that will be overcome with experience and a worthwhile price for a cleaner codebase. And, if we haven't forgotten it already, the Composition API is 100% non-breaking and does not hinder beginners from picking up the easy-to-grasp options based Vue API we all know and love.</p>
<h3 id="composingcompositionsonakeyboardkeyboard">Composing compositions on a keyboard-keyboard</h3>
<p>As a light-hearted and thoroughly informative and entertaining dive into the Composition API, <a href="https://github.com/ycmjason">Jason Yu</a>'s live-coding demo of <a href="https://www.youtube.com/watch?v=_K5zbgJ_z9w">Keyboard-Keyboard</a> was certainly the highlight of the conference on sheer entertainment value. Jason's humour, confidence and approachability balanced his presentation's role of showcasing the features and benefits of Composition Functions while communicating the pure joy he finds in both creating code and music.</p>
<h3 id="youhasthefinalsay">You has the final say</h3>
<p>As always,  Evan You concluded Vue.js London with updates on the progress of Vue 3.0. Probably in a follow up to the update given the year prior, this year's update centred around Vue's internals, with key compiler optimisations made. In keeping with the spirit of doing things &quot;live&quot; at conference, Evan officially open sourced the Vue 3.0 branch on GitHub in the strongest indication yet of the imminent arrival of Vue's next version.</p>
<h3 id="conclusion">Conclusion</h3>
<p>The underlying theme of creating performant and polished applications with Vue.js is certainly a testament to the progress both core contributors and the wider community has made in recent months and years. As concepts in one ecosystem gain traction and acceptance as &quot;best practices&quot;, it is my hope to be still challenged by new approaches and the cross-pollination of ideas between frameworks and communities. Finally, credit must be extended to Vue.js London organiser Blake Newman and his team for another successful edition of the conference.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Unit Testing in Vue.js: From Theory into Practice]]></title><description><![CDATA[<!--kg-card-begin: markdown--><iframe style="width: 100%; height: 480px;" src="//slides.com/andrewbeng89/vue-unit-testing/embed" scrolling="no" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen></iframe>
<p><em>First presented at <a href="https://www.meetup.com/Hamburg-Vue-js-Meetup/events/259509665/">Hamburg Vue.js Meetup #5</a></em></p>
<h3 id="testingtimes">Testing Times</h3>
<p>Quality assurance for software products and services typically spans multiple teams from project owners and managed to designers, and even dedicated QA teams. The standardised adoption of CI/CD pipelines to deliver software has allowed automated testing to become part</p>]]></description><link>http://blog.andrewbeng89.me/unit-testing-in-vue-js-from-theory-into-practice/</link><guid isPermaLink="false">5c9cdd873577953882d87290</guid><dc:creator><![CDATA[Andrew Beng]]></dc:creator><pubDate>Tue, 07 May 2019 20:47:34 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1518133910546-b6c2fb7d79e3?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=1080&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><iframe style="width: 100%; height: 480px;" src="//slides.com/andrewbeng89/vue-unit-testing/embed" scrolling="no" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen></iframe>
<img src="https://images.unsplash.com/photo-1518133910546-b6c2fb7d79e3?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="Unit Testing in Vue.js: From Theory into Practice"><p><em>First presented at <a href="https://www.meetup.com/Hamburg-Vue-js-Meetup/events/259509665/">Hamburg Vue.js Meetup #5</a></em></p>
<h3 id="testingtimes">Testing Times</h3>
<p>Quality assurance for software products and services typically spans multiple teams from project owners and managed to designers, and even dedicated QA teams. The standardised adoption of CI/CD pipelines to deliver software has allowed automated testing to become part of day-to-day DevOps. Automated software testing can generally be categorised into three groups, visually represented by the Testing Pyramid; 1. Unit Testing, 2. Integration Testing, and 3. End-to-end Testing. The layers of the pyramid visually quantify the proportion of each type of test <em>should be</em> covered within a software project.</p>
<p>Test-driven Development (TDD) is a software development process which is focused on QA and Unit Testing from the moment a developer writes their first line of code. In its &quot;purest&quot; form, TDD always begins with writing a unit test, and ends when the software written against the test passes the test.</p>
<h3 id="whatisunittestinganyway">What <em>is</em> Unit Testing anyway?</h3>
<p>Unit Testing has a very simple definition:</p>
<blockquote>
<p>Testing individual software units in isolation.</p>
</blockquote>
<p>Going further, a software unit can be defined as:</p>
<blockquote>
<p>The smallest, testable part of a software</p>
</blockquote>
<p>In the world of Functional Programming (FP), pure functions are the undisputed units to write tests for. Consider, for example, the factorial function where each value of <code>n</code> always produces a corresponding term:</p>
<pre><code class="language-js">/** The factorial! 😂 function
  * i.e. the product of all positive integers
  * less than or equal to n
  * n!=1.2.3.4...(n−2).(n−1).n
  * n!=n.(n−1)!
  */
const factorial = n =&gt; {
  if (n === 1) {
    return 1;
  }
  return n * factorial(n - 1);
};
</code></pre>
<p>A Vuex store module may similarly composed of different <code>mutation</code> and/or <code>getter</code> functions:</p>
<pre><code class="language-js">const state = { myList: [] };

const addListItem = (
  state, listItem
) =&gt; {
  state.myList = [
      ...state.myList,
      listItem
  ];
};

const mutations = { addListItem };

export default {
  state,
  mutations,
  namespaced: true
};
</code></pre>
<p>Things get a little more interesting once components are added to the equation:</p>
<pre><code class="language-html">&lt;template&gt;
    &lt;!-- Vue template markup --&gt;
&lt;/template&gt;

&lt;script&gt;
export default Vue.extend({
    // Vue component logic
    props: { /* some props */ },
    methods: { /* some methods */ }
});
&lt;/script&gt;

&lt;style&gt;
// Vue component styling
&lt;/style&gt;
</code></pre>
<p>But what about more complex (and typical) Vue.js components which map Vuex functionality:</p>
<pre><code class="language-html">&lt;template&gt;
    &lt;div&gt;
        &lt;button @click=&quot;fetchList&quot; /&gt;
    &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default Vue.extend({
    // Vue component logic
    props: { /* some props */ },
    methods: {
        ...mapActions(&quot;list&quot;, [
            &quot;fetchList&quot;
        ]
    }
});
&lt;/script&gt;

&lt;style&gt;
// Vue component styling
&lt;/style&gt;
</code></pre>
<p>In this scenario, the last two words in the Unit Testing definition plays its crucial role; <em>in isolation</em>. Testing the <code>fetchList</code> click handler against this component would not be <em>necessary</em> as the actual implementation would already have been tested when the Vuex store was created.</p>
<p>The general rule of &quot;do not test dependencies and dependants&quot; can be applied when unit testing mid-to-high complexity Vue.js components:</p>
<ul>
<li>Avoid directly test Vuex store functions</li>
<li>Avoid testing UI/CSS libraries, e.g. Vuetify, material-web-components</li>
<li>Avoid testing API modules</li>
<li>Avoid testing ...anything producing side-effects</li>
</ul>
<h3 id="triedandtested">Tried-and-tested</h3>
<p>As developers, and part of a wider product development team, the benefits of adopting Unit Testing as part of the development process are wide ranging. From the perspective of a developer, a TDD approach with an emphasis on unit testing generally results in code which is more modular (complex architectures composed from units), predictable, and ultimately maintainable. Similarly, from a product lifecycle perspective, creating unit test scripts early in the sprint enables the developer to clarify any vague acceptance criteria with the product owner before implementing features.</p>
<p>A familiar TDD cycle may look something like this:</p>
<ol>
<li>Write a failing test against the acceptance criteria (clarify if necessary)</li>
<li>Implement the feature in code</li>
<li>Run the code against the test</li>
<li>Repeat steps 2-3 until all tests scenarios for the unit pass</li>
</ol>
<p>With <code>vue-cli 3</code>, setting up a new or existing Vue.js project for unit testing is a breeze with a single entered in the terminal (or graphically with the Vue CLI UI):</p>
<pre><code>$ vue add @vue/unit-jest
</code></pre>
<p>Other automated development tooling including git pre-commit hooks and pre-build scripts for CI/CD allow developers to take their minds off when and how to run unit tests, focusing their efforts instead on delivering reliable features and enhancements.</p>
<h3 id="a5pointapproach">A 5-point Approach</h3>
<p>Moving towards a TDD-based process may seem daunting, but thinking about an approach with these general points could be beneficial:</p>
<ol>
<li>Apply white-box testing</li>
</ol>
<p>White-box testing involves isolating software units in a testing environment and testing provided input against some expected output. In contrast to black-box testing, where the implementation details of the software tested are opaque, white-box testing requires transparent knowledge of the units implementation. This becomes apparent when unit testing more complex parts of a Vue.js app, for instance an action function in a Vuex store. The <a href="https://slides.com/andrewbeng89/vue-unit-testing#/6">presentation above</a> visually describes the difference between white-box, black-box (E2E) and grey-box (integration) testing.</p>
<ol start="2">
<li>Validate scenarios using simple assertions</li>
</ol>
<p>The saying &quot;simpler is better&quot; applies to the approach of asserting input against output. If a function is expected return an array with three strings, the following assertion is something to <em>avoid</em>:</p>
<pre><code class="language-js">expect(array).toHaveLength(3);
expect(array[0]).toBe(&quot;quick&quot;);
expect(array[1]).toBe(&quot;brown&quot;);
expect(array[2]).toBe(&quot;fox&quot;);
</code></pre>
<p>This assertion is direct and understandable:</p>
<pre><code class="language-js">expect(array).toEqual([&quot;quick&quot;, &quot;brown&quot;, &quot;fox&quot;]);
</code></pre>
<p>With the previous example of the factorial function, the assertion below using Jest verifies whether the function works in finding the 5th and 10th factorial expressions:</p>
<pre><code class="language-js">it(&quot;Should return the nth factorial&quot;, () =&gt; {
  expect(factorial(5)).toBe(120);
  expect(factorial(10)).toBe(3628800);
});
</code></pre>
<p>The presentation and <a href="https://github.com/eddyerburgh/testing-vue-workshop">accompanying repository</a> provides more examples in creating assertions for Vuex mutations/getters and actions (with Jest mocks).</p>
<ol start="3">
<li>Ensure tests are run in an isolated environment (i.e. tests do not change the state of any other part of the software/system)</li>
<li>Pick the appropriate (i.e. well supported) tooling</li>
</ol>
<ul>
<li>framework/runner/assertion library</li>
</ul>
<p>Many frameworks provide officially supported unit testing frameworks where developers do not have to worry much about configuration. With <a href="https://vue-test-utils.vuejs.org/">vue-test-utils</a>, out-of-the-box unit testing is provided with Jest serving not only as the test framework, but also the runner and assertion library.</p>
<p>With <code>vue-test-utils</code>, individual Vue components are mounted in isolation to a JSDOM environment via a <a href="https://vue-test-utils.vuejs.org/api/wrapper/">wrapper based API</a> with the <code>shallowMount</code> method. Unlike <code>mount</code>, <code>shallowMount</code> <a href="https://slides.com/andrewbeng89/vue-unit-testing#/10/3">stubs a component's children components</a> rather than the entire subtree.</p>
<p>When unit testing Vue components, deciding which areas of code should be covered by tests can be complicated:</p>
<blockquote>
<p>we recommend writing tests that assert your component's public interface ...<br>
A component's interface comprises several inputs and their corresponding outputs:</p>
</blockquote>
<ul>
<li>Inputs: props, user interaction, Vuex store</li>
<li>Outputs: events, rendered/updated UI, mutations, actions</li>
</ul>
<p>A subjective but practical approach to minimise duplication when testing would be to exclude testing of any of the Vuex related features (e.g. <code>mapActions</code> or <code>mapMutations</code>) within a <code>.vue</code> SFC component, as coverage should have been provided when the store was implemented. These features are not directly covered directly by the <a href="https://slides.com/andrewbeng89/vue-unit-testing#/10/5">component's contract</a>.</p>
<p>Snapshot testing may also be a quick way of providing plenty of coverage with very few lines of test code. However, the following caveats need to be considered:</p>
<ul>
<li>Large snapshot files generated</li>
<li>False positives/negatives</li>
<li>Deterministic testing</li>
</ul>
<ol start="5">
<li>Use minimal mocking</li>
</ol>
<p>While Jest provides an excellent solution for mocking functions, modules and dependencies, relying on many mocks in a single unit signs is a likely indication of tight coupling and over-complexity of the code, and indication often described as a &quot;<a href="https://medium.com/javascript-scene/mocking-is-a-code-smell-944a70c90a6a">code smell</a>&quot;. In these cases, the software could likely be broken down into smaller units.</p>
<h3 id="wrappingitup">Wrapping it up!</h3>
<p>What this presentation and article hopes to inspire is that unit testing (with Vue.js and in general) is an easy process to adopt within a development team. Start (unit) testing NOW! When coupled with sound software design principles (like <a href="https://sites.google.com/site/unclebobconsultingllc/getting-a-solid-start">SOLID</a>), coding and testing software becomes a question of <em>which parts</em> of the codebase should be covered, rather than <em>how many lines</em>.</p>
<p>Beyond unit testing, the topic of integration testing still holds many unanswered questions; from experience, most bugs encountered in the wild are the result of integration related issues (e.g. changed API assumptions/requirements). However, setting up good integration tests is orders of magnitude more complex than unit testing. The <a href="https://slides.com/andrewbeng89/vue-unit-testing#/14">last section</a> of the presentation covers some basic aspects of integration testing within Vue.js apps (Vuex + <code>.vue</code> integration and Parent-Child integration).</p>
<h3 id="references">References</h3>
<ul>
<li><a href="http://softwaretestingfundamentals.com/">Software Testing Fundamentals</a></li>
<li><a href="https://www.manning.com/books/testing-vue-js-applications">Testing Vue.js Applications</a></li>
<li>Vue.js Testing Workshop by Edd Yerburgh
<ul>
<li><a href="https://slides.com/eddyerburgh/testing-vue-workshop#/">Slides</a></li>
<li><a href="https://github.com/eddyerburgh/testing-vue-workshop">Repo</a></li>
</ul>
</li>
<li>JavaScript Scene
<ul>
<li><a href="https://medium.com/javascript-scene/rethinking-unit-test-assertions-55f59358253f">Unit testing the RITE way</a></li>
<li><a href="https://medium.com/javascript-scene/tdd-changed-my-life-5af0ce099f80">TDD</a></li>
</ul>
</li>
<li>Companion <a href="https://github.com/andrewbeng89/vue-unit-testing">repo</a></li>
<li>More complex <a href="https://github.com/factorial-io/undo-redo-vuex/tree/master/tests/unit">scenarios</a></li>
</ul>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Building Towards a Reusable, Modular Web: iFrames and Web Components]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Websites and web applications often require embedding of some content or core business logic from third-parties. Think of videos provided by YouTube, or maps from Google Maps. For a long time, we have turned to HTML iFrame technology to implement these features. With the introduction of Web Components and the</p>]]></description><link>http://blog.andrewbeng89.me/building-towards-a-reusable-modular-web-iframes-and-web-components/</link><guid isPermaLink="false">5c9895703577953882d871e2</guid><category><![CDATA[frontend]]></category><category><![CDATA[javascript]]></category><category><![CDATA[web components]]></category><dc:creator><![CDATA[Andrew Beng]]></dc:creator><pubDate>Mon, 25 Mar 2019 09:03:10 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1536735561749-fc87494598cb?ixlib=rb-1.2.1&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;cs=tinysrgb&amp;w=1080&amp;fit=max&amp;ixid=eyJhcHBfaWQiOjExNzczfQ" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><img src="https://images.unsplash.com/photo-1536735561749-fc87494598cb?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ" alt="Building Towards a Reusable, Modular Web: iFrames and Web Components"><p>Websites and web applications often require embedding of some content or core business logic from third-parties. Think of videos provided by YouTube, or maps from Google Maps. For a long time, we have turned to HTML iFrame technology to implement these features. With the introduction of Web Components and the promise of &quot;reusable and encapsulated&quot; functionality, what then does the future hold for iFrame technology?</p>
<h3 id="iframebackgroundandusecases">iFrame – Background and Use Cases</h3>
<p>The iFrame or <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe">Inline Frame element</a> is used to embed another HTML document into the body of the currently browsed page. This creates a nested browsing context in which useful content from third-party sites or services can be directly enclosed without much configuration. A second and related use-case for iFrames is to enable reuse of business logic already implemented in an existing web application as embedded widgets (think of real-time chat widgets).</p>
<h3 id="drawbacksofiframetechnology">Drawbacks of iFrame technology</h3>
<p>There are, however, several drawbacks in using iFrames for either of the use-cases described. These include (and are not limited to):</p>
<ol>
<li>The nested context created in embedded pages could result in decreased SEO credit for the host page, as search engines will attribute content to the iFrame's source URL.</li>
<li>iFrames effectively create &quot;browser windows&quot; within the existing page, a potential User Experience nightmare resulting in unintended nested and vertical scrollbars if not carefully configured.</li>
<li>The isolated browsing context of an iFrame means that any link within an iFrame will redirect the iFrame's location to that link, while remaining on the original host URL inside the web browser.</li>
</ol>
<p>Despite these drawbacks, <a href="https://blog.futtta.be/2010/03/03/5-tips-to-tackle-the-problem-with-iframes/">precautions</a> can be taken to minimise and event eliminate problems faced.</p>
<h3 id="thepromiseofwebcomponents">The Promise of Web Components</h3>
<p>Enter Web Components; a set of four web technologies to help developers implement customised UI controls which are strongly encapsulated (non-conflicting) and reusable (modular and composable).</p>
<ol>
<li>The <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements">Custom Elements</a> API enable custom HTML elements (named and defined with custom attributes/events) to be defined and used like any other element.</li>
<li>The <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM">Shadow DOM</a> API allows an encapsulated DOM element which is attached to a host DOM element. CSS styles applied in the Shadow DOM will not bleed into the host document, and vice versa.</li>
<li>The <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots">HTML Templates</a> API provides <template> and <slot> tags to easily markup UI for reuse, without rendering them.</slot></template></li>
<li>The <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/HTML_Imports">HTML Import</a> API allows the import of Web Components from separate resource definitions.</li>
</ol>
<p>Together, Web Components technology points towards a future of more streamlined, less repetitive (more DRY - don't repeat yourself!), and extensible web application development. Weather widgets which have to &quot;look and feel&quot; different across multiple sites will no longer custom development in multiple projects. Instead, a custom <weather> element could be developed once and potentially imported, configured and run on any other site.</weather></p>
<h3 id="thefutureisnow">The Future is Now</h3>
<p>Given the lofty promise of Web Components, the reality of limited developer tools and <a href="https://github.com/vuejs/vue-web-component-wrapper#compatibility">poor browser compatibility</a> mean that this future will not be realised soon. As developers, we can only realistically target newer, feature-ready browsers like Chrome or Firefox, and not evergreen browsers which are still part of hard requirements set by clients. Choice is also limited when it comes to libraries and frameworks to build Web Components in:</p>
<ul>
<li>Create <a href="https://www.codementor.io/ayushgupta/vanilla-js-web-components-chguq8goz">&quot;Vanilla&quot; web components</a> using the &quot;(non-)standard&quot; Web Component APIs</li>
<li><a href="https://www.polymer-project.org/">Polymer</a>: library developed by Google to build and distribute web components</li>
<li>Wrapping other web app libraries by registering Vue/React/Angular components as Web Components
<ul>
<li><a href="https://github.com/vuejs/vue-web-component-wrapper">Vue-web-component-wrapper</a> (Web Component as build target in Vue CLI)</li>
<li><a href="https://github.com/ChristophP/web-react-components">Web-react-components</a></li>
</ul>
</li>
</ul>
<h3 id="handsonfactorialandconclusion">Hands-on @ Factorial and Conclusion</h3>
<p>At Factorial, we combined our experience with Vue.js development in delivering two Web Components based projects. The first was a real-time chat interfacing integrated in a hybrid Drupal 7/Socket.IO setup. The second project was a reusable UI component library proof-of-concept targeted at progressive, decentralised design overhaul across a suite of existing web apps. The first-class developer experience the Vue.js ecosystem provides made creating reusable Web Components a breeze compared to &quot;vanilla&quot; or Polymer approaches. We hope that support for targeting Web Component builds will mature over time and across more frontend frameworks.</p>
<p>In conclusion, despite its shortcomings, iFrame technology looks set to stay for the foreseeable future. For the core use-case of embedding content like videos and maps, iFrame solutions are quick, dependable and well documented by providers. For more complex use-cases in building reusable and modular interfaces, Web Component technology is exciting and promising. It now requires a concerted effort from browser vendors, UI framework contributors, and us as web developers to drive Web Components forward.</p>
<p><em>This article was first published on the Factorial Blog <a href="https://www.factorial.io/en/blog/2018/07/11/web-components/">here</a></em></p>
<!--kg-card-end: markdown-->]]></content:encoded></item></channel></rss>