2

I have an inline script that call a function declared in an external script. Unfortunately the inline script is executed before the external script is loaded and a function undefined error appear.

      <Helmet>
        <script
          src="https://code.jquery.com/jquery-3.3.1.min.js"
          integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
          crossorigin="anonymous"
        />
        <script>
          {`
            console.log('Test', typeof $);
          `}
        </script>
      </Helmet>

The issue can be seen here:

https://codesandbox.io/s/l9qmrwxqzq

It suddenly works if the page is refreshed by inserting some characters right after the closing helmet tag, but at first load the function remain undefined.

Tried multiple things like declaring both as helmet params, or inserting them in separate helmet tags but none of these worked.

neptune
  • 1,211
  • 2
  • 19
  • 32

1 Answers1

0

I deleted a few questionable characters. Now it seems to work for me:

<Helmet>
    <script
      src="https://code.jquery.com/jquery-3.3.1.min.js"
      integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
      crossorigin="anonymous"
    >
    </script>
    <script>
        console.log('Test: ', typeof $);          
    </script>
</Helmet>

I'm guessing the backticks and squiggly brackets aren't doing what you thought they might do. ( Usage of the backtick character (`) in JavaScript ).

Or perhaps the "self-closing tag" which works great with other tags is not working with the "script" tag (see Why don't self-closing script elements work? ), so it helps when I manually end the script with an end-script tag.

(Related?: CDN-script in Helmet does not always load properly )

David Cary
  • 5,250
  • 6
  • 53
  • 66
  • This may work for this particular case, but it seem I can't include a variable from the react component without backticks: https://codesandbox.io/s/react-helmet-loading-script-9kdbp?file=/src/index.js – neptune May 11 '20 at 20:36