'Embedding external script into Next.js application

I've been trying to embed an external JavaScript source into my Next.js application and keep receiving following error:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

The code I am trying to use can be found here - The map with the vessel has an option to embed it. So far the component that generates this error looks like this:

<div className={styles['container']}>
    <Script type="text/javascript">
        var width="100%";var height="400"; var mmsi=228402900;
    </Script>
    <Script
        type="text/javascript"
        src="https://www.vesselfinder.com/aismap.js">
    </Script>
</div>

If I copy the embed code into CodePen it works just fine - link to my codepen with the embedded map here.

Does somebody know what could be the problem here?



Solution 1:[1]

The issue occurs because the external script is being loaded asynchronously by next/script, thus ignoring the document.write() call present in the script.

From Document.write() MDN documentation:

Note: Using document.write() in deferred or asynchronous scripts will be ignored and you'll get a message like "A call to document.write() from an asynchronously-loaded external script was ignored" in the error console.

You'll need to set the Script strategy to beforeInteractive so the script is added to <head>, and explicitly set the defer property to false to prevent the script from being loaded asynchronously.

<Script
    type="text/javascript"
    src="https://www.vesselfinder.com/aismap.js"
    strategy="beforeInteractive"
    defer={false}
></Script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 juliomalves