To check if a specific script has already been loaded in a Razor .cshtml page, you can use a combination of C# and JavaScript. The C# code will generate a JavaScript variable in the header, and then you can use JavaScript to check for the existence of that variable and determine if the script has been loaded.
Here’s how you can do it:
- In your Razor .cshtml page, use C# to set a JavaScript variable in the header section. You can conditionally set the variable based on whether the script has already been loaded or not.
@{
// Set your script source URL here
string scriptSrc = "your-script-source.js";
// Check if the script is already loaded by inspecting the RenderedScripts collection
bool isScriptLoaded = PageContext.HttpContext.Items["RenderedScripts"]?.ToString().Contains(scriptSrc) ?? false;
// Set a JavaScript variable to indicate if the script is already loaded
<script>
var isScriptLoaded = @isScriptLoaded.ToString().ToLower();
</script>
}
Now, in your JavaScript section, you can access the isScriptLoaded
variable to check if the script has been loaded.
<script>
// Your other JavaScript code here...
if (isScriptLoaded) {
console.log("The script has already been loaded.");
// Do something if the script is already loaded
} else {
console.log("The script has not been loaded yet.");
// Do something else if the script has not been loaded
}
</script>
The C# code in the header section sets the isScriptLoaded
variable based on whether the script is found in the RenderedScripts
collection. The RenderedScripts
collection contains the URLs of scripts that have already been rendered on the page. We use ToString().Contains(scriptSrc)
to check if the scriptSrc
is present in the collection.
In the JavaScript section, we access the isScriptLoaded
variable to perform actions based on whether the script has been loaded or not.
This way, you can check if a specific script has already been loaded in the header of your Razor .cshtml page using a combination of C# and JavaScript.