I need to load a custom JS function I wrote at the beginning of the page load in a Docusaurus documentation site.
What have I tried so far?
Attempt #1: Appending the script to the index.js file (.\src\components\HomepageFeatures\index.js)
This attempt worked well during testing but then yarn
was not able to build the project anymore. The error was as follows:
[ERROR] Docusaurus server-side rendering could not render static page with path /. [INFO] It looks like you are using code that should run on the client-side only. To get around it, try using
<BrowserOnly>
(https://docusaurus.io/docs/docusaurus-core/#browseronly) orExecutionEnvironment
(https://docusaurus.io/docs/docusaurus-core/#executionenvironment). It might also require to wrap your client code inuseEffect
hook and/or import a third-party library dynamically (if any).
Attempt #2: To counter the issue presented during my first attempt, I created a separate (.js) file in (./src/js/myfunction.js) and then tried to load that file. To keep this question short, I will add a sample script below to showcase the issue:
import BrowserOnly from '@docusaurus/BrowserOnly';
<BrowserOnly>
window.onload = function() {
alert("Welcome!");
}
</BrowserOnly>
Then I went to the Docusaurus config file and added the following:
scripts: [
{
src: './src/js/myfunction.js',
async: false,
},
],
The site was built successfully this time, but the function was not getting loaded. I tried to call the function as well but still, I was getting nothing. I think I don't understand how the <BrowserOnly>
feature works or I am missing something else.
Your help will be much appreciated!
I solved the issue eventually by adjusting the custom-made JS file as follows:
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
if (ExecutionEnvironment.canUseDOM) {
// My own custom JS code.
}
Thereafter, I loaded that custom JS file from the config file (docusaurus.config.js) by adding the following:
clientModules: [
require.resolve('./path-to-custom-code/custom-code.js'),
],
This has been mentioned briefly in the documentation but it wasn't clear at all. The documentation of Docusaurus requires more elaboration and examples.
You can view it here though: https://docusaurus.io/docs/advanced/client#client-modules
If anyone has a better approach, please add it to this post. Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With