Skip to content

Commit

Permalink
feat(v2): lazy load algolia css so its not render blocking (#2125)
Browse files Browse the repository at this point in the history
* perf(v2): algolia css should not be render blocking

* tweak

* lazy load css

* tweak

* tweak

* review
  • Loading branch information
endiliey authored Dec 15, 2019
1 parent b6315f4 commit dcf1fef
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 13 deletions.
20 changes: 20 additions & 0 deletions packages/docusaurus-theme-search-algolia/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
},
},
},
};
},
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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();
}
Expand Down Expand Up @@ -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}
Expand Down
1 change: 1 addition & 0 deletions packages/docusaurus/src/webpack/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit dcf1fef

Please sign in to comment.