Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[1.0] optimizations around prefetching page resources #1133

Merged
merged 29 commits into from
Jun 10, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
c0ae4f9
Copy cache-dir files into site's .cache
KyleAMathews Jun 7, 2017
291b69c
Got new loader/componentrenderer working in development
KyleAMathews Jun 7, 2017
f92fdb9
Use ComponentRenderer for rendering
KyleAMathews Jun 7, 2017
f6c3112
On demand loading of async page resources working for prod builds
KyleAMathews Jun 7, 2017
d0ae0e6
Merge branch '1.0' into queue-requests
KyleAMathews Jun 7, 2017
0c8abd7
Use script loader so loading scripts don't block rendering
KyleAMathews Jun 7, 2017
69f60ae
Add gatsby-module-loader to replace bundle-loader to add ability to d…
KyleAMathews Jun 8, 2017
1f44c11
Split out loading/executing resources into functions
KyleAMathews Jun 8, 2017
f289c38
Add prefetcher
KyleAMathews Jun 8, 2017
389f7e9
changing order to see if it fixes not removing event handler
KyleAMathews Jun 8, 2017
b0f2c88
Just don't have a loader for now
KyleAMathews Jun 8, 2017
d4a841b
Updates to service worker plugin
KyleAMathews Jun 9, 2017
f2f368b
Add tests for find-page + make it work with prefixed links
KyleAMathews Jun 9, 2017
9ae6a60
Proritize links that mount first i.e. are higher on the page
KyleAMathews Jun 9, 2017
7766b77
Wait for all links to mount before fetching so resource count is correct
KyleAMathews Jun 9, 2017
ab5da7f
Add plop template for adding new example sites
KyleAMathews Jun 10, 2017
c7dd9b1
Add plugin for nprogress to auto show when page loading is delayed
KyleAMathews Jun 10, 2017
4644ea7
Don't break layout if there's no content
KyleAMathews Jun 10, 2017
aeb9a77
Log at end of build how long build took
KyleAMathews Jun 10, 2017
8162a91
Not using this package
KyleAMathews Jun 10, 2017
bbf5302
Merge remote-tracking branch 'origin/1.0' into queue-requests
KyleAMathews Jun 10, 2017
19f7c72
Remove logging + run format
KyleAMathews Jun 10, 2017
a1fd507
Add the nprogress plugin
KyleAMathews Jun 10, 2017
ce5ca59
Fix some emitter code
KyleAMathews Jun 10, 2017
ab0e3f4
Make it easy to override the default color of the nprogress bar
KyleAMathews Jun 10, 2017
33e9e8e
Fix check on variable
KyleAMathews Jun 10, 2017
c6b486a
Fix prefetching
KyleAMathews Jun 10, 2017
6cac6e1
Fix test
KyleAMathews Jun 10, 2017
fd01c58
Add nprogress plugin to list
KyleAMathews Jun 10, 2017
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Split out loading/executing resources into functions
  • Loading branch information
KyleAMathews committed Jun 8, 2017
commit 1f44c111ba3211844993e23c4fc202a93df5901a
1 change: 1 addition & 0 deletions packages/gatsby/src/cache-dir/component-renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class ComponentRenderer extends React.Component {
componentDidMount() {
// listen to events.
___emitter.on(`onPostLoadPageResources`, e => {
console.log("onPostLoadPageResources", e)
if (e.page.path === this.props.location.pathname) {
this.setState({ pageResources: e.pageResources })
}
Expand Down
99 changes: 83 additions & 16 deletions packages/gatsby/src/cache-dir/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ let findPage
let syncRequires = {}
let asyncRequires = {}
let pathScriptsCache = {}
let resourceStrCache = {}
let resourceCache = {}
let pages = []
// Note we're not actively using the path data atm. There
// could be future optimizations however around trying to ensure
Expand Down Expand Up @@ -38,7 +40,75 @@ const sortPagesByCount = (a, b) => {
}
}

const prefetcher = () => {}
const fetchResource = (resourceName, cb = () => {}) => {
if (resourceStrCache[resourceName]) {
return resourceStrCache[resourceName]
} else {
// Find resource
const resourceFunction = resourceName.slice(0, 6) === `page-c`
? asyncRequires.components[resourceName]
: asyncRequires.json[resourceName]

// Download the resource
console.time(`download resource ${resourceName}`)
resourceFunction((err, executeChunk) => {
console.timeEnd(`download resource ${resourceName}`)
resourceStrCache[resourceName] = executeChunk
cb(err, executeChunk)
})
}
}

const getResourceModule = (resourceName, cb) => {
if (resourceCache[resourceName]) {
return cb(null, resourceCache[resourceName])
} else {
fetchResource(resourceName, (err, executeChunk) => {
if (err) {
cb(err)
} else {
console.time(`execute chunk ${resourceName}`)
const module = preferDefault(executeChunk())
console.timeEnd(`execute chunk ${resourceName}`)
resourceCache[resourceName] = module
return cb(err, module)
}
})
}
}

// TODO split this into two functions, one for fetching
// resource and the other for executing it.
// This prefetcher just sits around waiting for
// new resources to be added. When hears onPreLoadPageResources
// it stops until it hears onPostLoadPageResources
// actually, make it a state machine like thing that's listening
// to events and flipping it's state around.
//
// This is stupid complex. Need tests somehow.
// const prefetcher = () => {
// // Get top resource and start downloading it.
// const nextResource = resourcesArray.slice(-1)[0]
// if (nextResource) {
// console.log("prefetching next resource", nextResource)
// fetchResource(nextResource, (err, executeChunk) => {
// console.log("executeChunk", executeChunk)
// resourcesArray = resourcesArray.filter(r => r !== nextResource)
// setTimeout(() => {
// console.time(`execute resource`)
// const module = getResourceModule(nextResource)
// console.timeEnd(`execute resource`)
// console.log("module", module)
// prefetcher()
// }, 500)
// })
// } else {
// // Wait a second and try again
// setTimeout(() => prefetcher(), 1000)
// }
// }

// setTimeout(() => prefetcher(), 2500)

const queue = {
empty: () => {
Expand Down Expand Up @@ -141,11 +211,9 @@ const queue = {
if (pathScriptsCache[path]) {
return pathScriptsCache[path]
}

console.log("need to load scripts")
const page = findPage(path)
console.log("for page", page)
console.log(`async requires`, asyncRequires)
let component
let json
const done = () => {
Expand All @@ -157,19 +225,18 @@ const queue = {
})
}
}
console.log(asyncRequires.components[page.componentChunkName])
console.log(asyncRequires.json[page.jsonName])
asyncRequires.components[page.componentChunkName]()(
callback => {
component = preferDefault(callback())
console.log(`page component`, component)
done()
},
() => console.log("error loading page component")
)
asyncRequires.json[page.jsonName]()(callback => {
json = preferDefault(callback())
console.log(`json`, json)
getResourceModule(page.componentChunkName, (err, c) => {
if (err) {
return console.log("we failed folks")
}
component = c
done()
})
getResourceModule(page.jsonName, (err, j) => {
if (err) {
return console.log("we failed folks")
}
json = j
done()
})
}
Expand Down
20 changes: 6 additions & 14 deletions packages/gatsby/src/loaders/gatsby-module-loader/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,12 @@
*/
const loaderUtils = require(`loader-utils`)
const path = require(`path`)
console.log("in gatsby-module-loader")

module.exports = function() {}
module.exports.pitch = function(remainingRequest) {
this.cacheable && this.cacheable()

console.log("this.query", this.query)
const query = loaderUtils.parseQuery(this.query)
console.log("query", query)
let chunkName = ``

if (query.name) {
Expand All @@ -25,22 +22,19 @@ module.exports.pitch = function(remainingRequest) {
chunkName = `, ${JSON.stringify(chunkName)}`
}

console.log(`chunkName`, chunkName)

const request = loaderUtils.stringifyRequest(this, `!!` + remainingRequest)

const callback = "callback(function() { return require(" + request + ") })"
const callback = "function() { return require(" + request + ") }"

const executor = `
return function(callback, errback) {
require.ensure([], function(_, error) {
return require.ensure([], function(_, error) {
if (error) {
errback()
cb(true)
} else {
${callback}
cb(null, ${callback})
}
}${chunkName});
}`
`

const result = `
require(
Expand All @@ -49,10 +43,8 @@ module.exports.pitch = function(remainingRequest) {
`!${path.join(__dirname, `patch.js`)}`
)}
);
module.exports = function() { ${executor} }
module.exports = function(cb) { ${executor} }
`

console.log(`result`, result)

return result
}
4 changes: 2 additions & 2 deletions packages/gatsby/src/loaders/gatsby-module-loader/patch.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,5 +76,5 @@ function patch() {
script.onload = script.onerror = null
setTimeout(callback, 0)
}
};
};
}
}