instantpage / instant.page

Make your site’s pages instant in 1 minute and improve your conversion rate by 1%
https://instant.page
MIT License
6.04k stars 205 forks source link

Check that a href element exists #12

Closed kyranb closed 5 years ago

kyranb commented 5 years ago

Following up from Issue #11

Ensure that instantclick ignores tags that do not have a href attribute (which is valid HTML as per the link below).

https://www.w3.org/TR/2016/REC-html51-20161101/textlevel-semantics.html#the-a-element

Samuell1 commented 5 years ago

Hey, i think there should be added javascript:; to ignore it too.

JohnMunsch commented 5 years ago

Another alternative is to put the code which creates the new URL into a try/catch block like so:

function isPreloadable(linkElement) {
  if (urlToPreload == linkElement.href) {
    return
  }

  if ('noInstant' in linkElement.dataset) {
    return
  }

  try {
    const urlObject = new URL(linkElement.href)

    if (urlObject.origin != location.origin) {
      return
    }

    if (!allowQueryString && urlObject.search && !('instant' in linkElement.dataset)) {
      return
    }

    if (urlObject.hash && urlObject.pathname + urlObject.search == location.pathname + location.search) {
      return
    }
  } catch {
    return
  }

  return true
}

Note: This version also moves the check for "data-no-instant" up above the other checks where it belongs. If I've said I'm not interested in this link being preloaded, that's the end of it.

dieulot commented 5 years ago

I’ve implemented it myself. Thanks anyway. A condition on !linkElement.href is enough. Your two other conditions can’t be hit because .href returns an absolute URL.