3/20/18

Creating Javascript Router With Vanilla Javascript

What is router?
Router is a way to get different content in response to changes of url.
example:

That way it easy to memorize the url, and also you are able to navigate exact to product you need by the link (/vehicle/297 will lead you to SV650).
But what it means when speaking about JavaScript? Can JavaScript change the url without triggering full refresh of page?

Yes You Can

 It appears that javascript can change the url with HTML5 feature:

window.history.pushState("object or string", "sv650", "/sv650");



But How To Subscribe To Url Changes?

Yes, there is another HTML5 feature for it:
You can subscribe to 'pushstate' event:


window.addEventListener('popstate', (e) => {
  ...
});

Here is stackblitz project demonstrating routing in action

Summary

In this post you have learned that all 'Router' thing is actually very simple, and can be achieved with few pure javascript commands...
If you need more customizations like 'hash' Here is navigo vanilla javascript router...

No comments:

Post a Comment

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...