To check if an inline script has already been loaded in the header of a Razor .cshtml page, you can use a similar approach as the one for checking external script loading. You’ll set a JavaScript variable in the header using C#, and then use JavaScript to check for the existence of that variable.

Here’s how you can do it:

  1. In your Razor .cshtml page, use C# to set a JavaScript variable in the header section. This variable will indicate whether the inline script has been loaded or not.
@{
    // Your inline script content here
    string inlineScript = "console.log('This is an inline script.');";

    // Check if the inline script is already loaded by inspecting the RenderedInlineScripts collection
    bool isInlineScriptLoaded = PageContext.HttpContext.Items["RenderedInlineScripts"]?.ToString().Contains(inlineScript) ?? false;

    // Set a JavaScript variable to indicate if the inline script is already loaded
    <script>
        var isInlineScriptLoaded = @isInlineScriptLoaded.ToString().ToLower();
    </script>
}

Now, in your JavaScript section, you can access the isInlineScriptLoaded variable to check if the inline script has been loaded.

<script>
    // Your other JavaScript code here...

    if (isInlineScriptLoaded) {
        console.log("The inline script has already been loaded.");
        // Do something if the inline script is already loaded
    } else {
        console.log("The inline script has not been loaded yet.");
        // Do something else if the inline script has not been loaded
    }
</script>

The C# code in the header section sets the isInlineScriptLoaded variable based on whether the inline script content is found in the RenderedInlineScripts collection. The RenderedInlineScripts collection contains the content of inline scripts that have already been rendered on the page. We use ToString().Contains(inlineScript) to check if the inlineScript content is present in the collection.

In the JavaScript section, we access the isInlineScriptLoaded variable to perform actions based on whether the inline script has been loaded or not.

Keep in mind that this approach only checks if the exact inline script content is present in the RenderedInlineScripts collection. If the inline script content has changed or if there are variations in whitespace or other characters, the check may not work as expected. If you need to perform more advanced checks, you may need to use other techniques or consider using external scripts instead.