jsakamoto / Toolbelt.Blazor.HeadElement

Head element support (change the document title, "meta" elements such as OGP, and "link" elements) for Blazor apps.
https://demo-blazor-headelement.azurewebsites.net/
Mozilla Public License 2.0
158 stars 11 forks source link

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

Open fingers10 opened 1 year ago

fingers10 commented 1 year ago

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.

jsakamoto commented 1 year ago

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

Alerinos commented 1 year ago

@fingers10 You can use this method as well.

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

@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..

Alerinos commented 1 year ago

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

fingers10 commented 1 year ago

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

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

jsakamoto commented 1 year ago

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.

Alerinos commented 1 year ago

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