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!