feat(v2): lazy load algolia css so its not render blocking (#2125)

* perf(v2): algolia css should not be render blocking

* tweak

* lazy load css

* tweak

* tweak

* review
This commit is contained in:
Endi 2019-12-15 16:43:46 +07:00 committed by GitHub
parent b6315f4136
commit dcf1fef001
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 33 additions and 13 deletions

View file

@ -14,5 +14,25 @@ module.exports = function() {
getThemePath() {
return path.resolve(__dirname, './theme');
},
configureWebpack() {
// Ensure that algolia docsearch css is its own chunk
return {
optimization: {
splitChunks: {
cacheGroups: {
algolia: {
name: 'algolia',
test: /algolia\.css$/,
chunks: `all`,
enforce: true,
// Set priority higher than docusaurus single-css extraction
priority: 60,
},
},
},
},
};
},
};
};

View file

@ -11,10 +11,7 @@ import classnames from 'classnames';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import {useHistory} from '@docusaurus/router';
import './styles.css';
const loadJS = () => import('docsearch.js');
let loadedJs = false;
let loaded = false;
const Search = props => {
const initialized = useRef(false);
@ -54,13 +51,15 @@ const Search = props => {
}
};
const loadAlgoliaJS = () => {
if (!loadedJs) {
loadJS().then(a => {
loadedJs = true;
window.docsearch = a.default;
initAlgolia();
});
const loadAlgolia = () => {
if (!loaded) {
Promise.all([import('docsearch.js'), import('./algolia.css')]).then(
([{default: docsearch}]) => {
loaded = true;
window.docsearch = docsearch;
initAlgolia();
},
);
} else {
initAlgolia();
}
@ -99,8 +98,8 @@ const Search = props => {
{'search-bar-expanded': props.isSearchBarExpanded},
{'search-bar': !props.isSearchBarExpanded},
)}
onClick={loadAlgoliaJS}
onMouseOver={loadAlgoliaJS}
onClick={loadAlgolia}
onMouseOver={loadAlgolia}
onFocus={toggleSearchIconClick}
onBlur={toggleSearchIconClick}
ref={searchBarRef}

View file

@ -180,6 +180,7 @@ export function createBaseConfig(
plugins: [
new MiniCssExtractPlugin({
filename: isProd ? '[name].[contenthash:8].css' : '[name].css',
chunkFilename: isProd ? '[name].[contenthash:8].css' : '[name].css',
// remove css order warnings if css imports are not sorted alphabetically
// see https://github.com/webpack-contrib/mini-css-extract-plugin/pull/422 for more reasoning
ignoreOrder: true,