1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/lib/link.js
Arunoda Susiripala 36abdc77c5 Prefetch pages with Service Workers (#375)
* Register the service worker.

* Update prefetcher code to do prefetching.

* Implement the core prefetching API.
support "import <Link>, { prefetch } from 'next/prefetch'"

* Implement a better communication system with the service worker.

* Add a separate example for prefetching

* Fix some typos.

* Initiate service worker support even prefetching is not used.
This is pretty important since initiating will reset the cache.
If we don't do this, it's possible to have old cached resources
after the user decided to remove all of the prefetching logic.
In this case, even the page didn't prefetch it'll use the
previously cached pages. That because of there might be a already running
service worker.

* Use url module to get pathname.

* Move prefetcher code to the client from pages
Now we also do a webpack build for the prefetcher code.

* Add prefetching docs to the README.md

* Fix some typo.

* Register service worker only if asked to prefetch
We also clean the cache always, even we initialize
the service worker or not.
2016-12-15 11:13:40 -08:00

70 lines
1.6 KiB
JavaScript

import React, { Component, PropTypes, Children } from 'react'
export default class Link extends Component {
static contextTypes = {
router: PropTypes.object
}
constructor (props) {
super(props)
this.linkClicked = this.linkClicked.bind(this)
}
linkClicked (e) {
if (e.target.nodeName === 'A' &&
(e.metaKey || e.ctrlKey || e.shiftKey || (e.nativeEvent && e.nativeEvent.which === 2))) {
// ignore click for new tab / new window behavior
return
}
const { href, scroll } = this.props
if (!isLocal(href)) {
// ignore click if it's outside our scope
return
}
e.preventDefault()
// straight up redirect
this.context.router.push(null, href)
.then((success) => {
if (!success) return
if (scroll !== false) window.scrollTo(0, 0)
})
.catch((err) => {
if (this.props.onError) this.props.onError(err)
})
}
render () {
const children = Children.map(this.props.children, (child) => {
const props = {
onClick: this.linkClicked
}
const isAnchor = child && child.type === 'a'
// if child does not specify a href, specify it
// so that repetition is not needed by the user
if (!isAnchor || !('href' in child.props)) {
props.href = this.props.href
}
if (isAnchor) {
return React.cloneElement(child, props)
} else {
return <a {...props}>{child}</a>
}
})
return children[0]
}
}
export function isLocal (href) {
const origin = window.location.origin
return !/^https?:\/\//.test(href) ||
origin === href.substr(0, origin.length)
}