JS: Let’s try the future today (extra bonus)

Written by paquitosoftware | Published 2017/10/21
Tech Story Tags: javascript | vanillajs | tutorial | js | safari

TLDRvia the TL;DR App

In a previous article I showed a way to implement a basic and simple application with no third party dependencies or build tools, just using all the new goodies have and the latests browsers have already implemented.

There’s an extra feature we can add to that application with little effort but, currently it only works in Safari, as it is the only browser which have implemented then dynamic import API.

With this API, we can defer the load of parts of the application code so the browser does not download it upfront.

What I want to implement now is the ability for the application to only download core code and current view code on page load so, if we load the home view (the one with the podcasts list), no code for the podcast detail view nor episode detail view are pulled by the browser.

So, we only have to change two files in our application to achieve this new feature.

(Remember yo can see the complete code of the application here. There’s a branch in the repository called async-routing with this feature implemented).

The strategy is to add an new step in the router navigation function so, before it renders the new page, it fetches the page-level component it needs to render.

I first need to change the routing configuration file so it doesn’t import the page-level components directly. Instead, I just set the relative path to the component (in this case, relative to the components folder):

Changes to routing configuration file

The only other thing I have to change is the router component so it grabs the corresponding file before trying to navigate.Here is the diff for this file:

Changes to router component file

So, the important line is the one with the import call. This will tell the browser to fetch the file we’ve configured in the routing config (it’ll only do it once).The import function returns a Promise which is resolved when the browser have loaded the required module file (and all its dependencies).

And, that’s it.Just a few more lines and we have implemented code splitting to our application.

Keep in mind that currently only Safari supports dynamic imports (Chrome will support it in its next version, v63).More status info: https://www.chromestatus.com/features/5684934484164608


Published by HackerNoon on 2017/10/21