kadirahq / meteor-dochead

Isomorphic way to manipulate document.head for Meteor apps

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Better check/remove API

CaptainN opened this issue · comments

I'd like to be able to add links only on some routes (or route groups), and remove them when I go to other routes, but there is no easy way to check if the link has been added, or to remove only a single tag. Flow Router also lacks the necessary hooks to make this smooth.

With Flow you can do it in triggersEnter but if you are navigating between pages that rely on bootstrap (for example) you'll get a flash of unstyled content between routes.

It would be nicer if there was a registry or some way to check if the tag has already been added. I propose the following:

  1. Add a method to remove links based on a globally unique field, such as href/src.
  2. Add a method to check if links are added based on a globally unique field such as href/src.
  3. Have the add methods return a handle that can be passed to a remove method, or that contains methods to manage the lifecyle of the link.

These methods would also help with issue #34

I'm happy to make a PR for these.

In case anyone is interested, I ended up creating a kind of watcher function in triggers.enter, which detects when the group changes (using a local state var), and adds or removes the link as necessary.

Using this pattern, each managing chunk of code (my main front end, and the flow-db-admin package) can control only their own bits, and I don't have to worry about removing everything all the time.

var currentGroup = ''
FlowRouter.triggers.enter([
  function onEnterTrigger (context) {
    // did the group change?
    if (!context.route.group || currentGroup !== context.route.group.name) {
      const clientLink = {
        rel: 'stylesheet',
        type: 'text/css',
        href: '/stylesheets/main.css'
      }
      currentGroup = context.route.group && context.route.group.name
      // my client routes either use no group (undefined), or 'admin'
      if (currentGroup === 'admin' || !currentGroup) {
        DocHead.addLink(clientLink)
      } else {
        DocHead.removeLink(clientLink)
        // may also clean up Blaze/React remnants here
      }
    }
  }
])

My fork of flow-db-admin does something similar for bootstrap and its own links.