DEV Community

Discussion on: A Router Without a Web Server in Vanilla JavaScript

Collapse
 
michdo93 profile image
Michdo93

Maybe a better solution is to use jQuery. I don`t have rewritten your code completly in jQuery. The only thing I changed is that I import .html template files with the jQuery function .load().

repl.it/@Michdo93/HummingParallelP...

I only want to show, that with easy changes you could create a much more useable solution. If you want to add as example a MVC pattern jQuery could also be a better choice. And if you want to fetch Data maybe over Ajax also jQuery make things much easier. And you have a simple solution, which is what modern frameworks do. MVC, Observer pattern and routing. You can do it only using pure JS or jQuery. The last one is an much easier way.

Collapse
 
aminnairi profile image
Amin

Hi there and thanks for contributing to this article!

That looks awesome rewritten in jQuery! I'm pretty sure people will find it very interesting. And for people that don't/can't use a framework, this example still remains relevant.

I would also like to add that you can go even further by using jQuery everywhere in this slightly updated example.

function onRouteChanged() {
  const hash = window.location.hash;
  const routerView = $("#router-view"); // updated

  if (!(routerView instanceof HTMLElement)) {
    throw new ReferenceError("No router view element available for rendering");
  }

  switch (hash) {
    case "#home":
      //routerView.innerHTML = "<h1>Home page</h1>";
      routerView.load('views/home.html'); // updated
      break;

    case "#about":
      //routerView.innerHTML = "<h1>About page</h1>";
      routerView.load('views/about.html'); // updated
      break;

    default:
      //routerView.innerHTML = "<h1>404 - Page Not Found</h1>";
      routerView.load('views/404.html'); // updated
      break;
  }
}

$(window).on("hashchange", onRouteChanged); // updated
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tangopj profile image
TangoPJ
Thread Thread
 
aminnairi profile image
Amin

That's really clever, well done!

Except styles don't apply to the <object> tag sadly and I think it would be very inconvenient to style elements using this technique and an external CSS file.

But if you are designing a markup-only web page this is the way to go (or use inline styles if you are brave enough).

But this is a great tag to render some multimedia content like videos or PDF files!

Thread Thread
 
tangopj profile image
TangoPJ

Yep, I have a problem with styling my content, I think how can I do that now. Thank you for your return