Toolbelt.Blazor.HeadElement icon indicating copy to clipboard operation
Toolbelt.Blazor.HeadElement copied to clipboard

[Feature Request] Ability to inject script tag into head element?

Open fingers10 opened this issue 3 years ago • 7 comments

Current in blazor wasm index.html there is now way to get environment and load scripts based on environment. If we add a feature to this package to inject script into head tag, It will be awesome.

fingers10 avatar Oct 23 '22 02:10 fingers10

@fingers10 Actually, injecting <script> elements dynamically is a more complicated task than you might think. Instead, would the following package help you?

  • https://www.nuget.org/packages/Sitko.Blazor.ScriptInjector

jsakamoto avatar Oct 24 '22 11:10 jsakamoto

@fingers10 You can use this method as well.

var module = await JS.InvokeAsync<IJSObjectReference>("import", "/lib/xxx.js");
await module.InvokeVoidAsync(xxx);

Alerinos avatar Oct 24 '22 12:10 Alerinos

@fingers10 You can use this method as well.

var module = await JS.InvokeAsync<IJSObjectReference>("import", "/lib/xxx.js");
await module.InvokeVoidAsync(xxx);

@Alerinos does this approach adds the script tag to head element? I would like to just add an script tag with src pointing to cdn conditionally..

fingers10 avatar Oct 24 '22 12:10 fingers10

@fingers10 Why can't you do this in _Layout?

Alerinos avatar Oct 24 '22 15:10 Alerinos

@fingers10 Why can't you do this in _Layout?

@Alerinos do you mean MainLayout.razor in blazor wasm?

fingers10 avatar Oct 24 '22 15:10 fingers10

Hi @Alerinos , Thank you for helping us!

By the way, I guess that @fingers10 is talking about his website "https://ilovedotnet.org/" (The source code is here). And that website is hosted on GitHub Pages. The website is a Blazor WebAssembly app without ASP.NET Core hosting, so he might not be able to take a server-side strategy such as you suggested.

Hi @fingers10,

@Alerinos do you mean MainLayout.razor in blazor wasm?

I think the answer is no, and he may not want to mean that. I guess the "_Layout" that he told us is an ASP.NET Core Razor Pages that run on server-side .NET processes. It is contained in Blazor Server or ASP.NET Core Host for Blazor WebAssembly.

jsakamoto avatar Oct 24 '22 23:10 jsakamoto

I understand, in that case you have to write JS code and then execute it in blazor.

Example:

JS.InvokeVoidc("loadJS", "url.js")

https://learn.microsoft.com/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-6.0

JS: https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file

Alerinos avatar Oct 24 '22 23:10 Alerinos