Reputation: 1297
I've a .js file which contains following javascript code:
<script>
abc= window.abc|| {};
abc.Metrics = abc.Metrics || {};
abc.Metrics.sc = abc.Metrics.sc || {};
abc.Metrics.sc.country = "us"; /***dynamic value based on site***/
abc.Metrics.sc.language = "en"; /***dynamic value based on site***/
abc.Metrics.sc.segment = "corp"; /***dynamic value based on site***/
abc.Metrics.sc.customerset = "19"; /***dynamic value based on site***/
abc.Metrics.sc.cms = "stp"; /***dynamic value based on site***/
abc.Metrics.sc.pagename = "pname"; /***relevant unique page name***/
abc.Metrics.sc.applicationname = "Browse:Product Detail";
</script>
<!-- Refer the below script in DEV -->
<script src="//gbxDev/Bootstrap.js"></script>
Now, I want to inject this piece of code from .cs file without adding the reference of this js file in _Host.cshtml. Also, I've to set those variable values dynamically at the startup. Is it possible in blazor server side?
Upvotes: 1
Views: 2062
Reputation: 968
You can add any js file dynamically with this way:
@code {
protected override async void OnAfterRender(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync(identifier: "import", "/js/yourfile.js");
}
}
}
The above code just lets you call. If you want to call with initial value you want to send. You should follow this way:
@code {
protected override async void OnAfterRender(bool firstRender)
{
String parameter1 = "test";
if (firstRender)
{
await JSRuntime.InvokeVoidAsync(identifier: "yourMethodName", parameter1);
}
}
}
JS File Side
window.yourMethodName= (parameter) => { *** }
*You have to add this js file in _host.cshtml
Upvotes: 6