Issues with Dynamically Injecting App Insights Script After Cookie Consent

I’m attempting to load the Microsoft Azure Application Insights script dynamically into the <head> tag after a user accepts cookies. However, I’ve run into an issue where the backslashes () within the JavaScript code are being removed, causing the script to break.

Here’s the relevant code snippet:

const scripts = `
    <script type="text/javascript">
        !(function (cfg) {
            // ... 
        })( {
            src: "https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js",
            crossOrigin: "anonymous",
            cfg: {
                connectionString: "InstrumentationKey=YOUR_INSTRUMENTATION_KEY"
            }
        });
    </script>
    <script type="text/javascript" language="javascript">
        var ref = document.referrer;
        appInsights.trackTrace({ message: 'Referrer  ' + ref });
    </script>
`;

I’ve implemented the following function to append the script to the head:

function addScripts() {
    $('head').append(scripts);
};

However, when I execute this function, the backslashes are stripped out, resulting in a corrupted script. I expected the script to load properly without losing any characters.