Search code examples
reactjsdocusaurus

Custom Inline Script with Docusaurus


I'm trying to add the wowhead tooltips to a docusaurus page.

The wowhead documentation suggests you need to add the following to your <head> section:

<script>const whTooltips = {colorLinks: true, iconizeLinks: true, renameLinks: true};</script>
<script src="https://wow.zamimg.com/widgets/power.js"></script>

I can add the https://wow.zamimg.com/widgets/power.js fine using the scripts configuration option which works fine with defer or async:

module.exports = {
  // Snipped rest of configuration
  scripts: [
    {
      src:
        'https://wow.zamimg.com/widgets/power.js',
      defer: true,
    },
  ],

For the inline portion <script>const whTooltips = {colorLinks: true, iconizeLinks: true, renameLinks: true};</script> I have tried using a <Head> component in my index.js <Layout> section and had no success.

How can I add this inline script properly to docusaurus so it loads before the wowhead script?


Solution

  • Using the advice from D.Kastier, I successfully solved my problem, granted it wasn't very elegant.

    To load the script properly, and have it update after the page initially loads:

         injectHtmlTags() {
           return {
             headTags: [
               // https://www.wowhead.com/tooltips
               {
                 tagName: 'script',
                 innerHTML: `
                   const whTooltips = {colorLinks: true, iconizeLinks: true, renameLinks: true};
    
                   document.addEventListener('readystatechange', event => {
                     if (event.target.readyState === "complete") {
                       console.log('Updating tooltips from plugin');
                       window.$WowheadPower.refreshLinks();
                     }
                    });
                 `,
               },
               {
                 tagName: 'script',
                 attributes: {
                   defer: true,
                   src: 'https://wow.zamimg.com/widgets/power.js',
                 },
               },
             ],
           };
         },
    

    Then to update the tooltips each time the page changes:

        onRouteUpdate({location}) {
          setTimeout(function() {           
              window.$WowheadPower.refreshLinks(); 
            }, 0);
        },