aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

How to generate/emit dynamically build JS into the Client's Browser from SSR Blazor page?

Open htmlsplash opened this issue 1 year ago • 0 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Is your feature request related to a problem? Please describe the problem.

Request, or help/suggestion needed for:

Our application generates and emits java script dynamically into the client page. This was a common pattern in Webforms to register a startup or client script on the server based on some state and run it once in the client's browser.

We would like to do the same from within the SSR page in Blazor (avoiding a web socket connect, ie. non-interactive).

I have reviewed the following:

ASP.NET Core Blazor JavaScript with static server-side rendering (static SSR) and reported issue: #51331

This provides only partial solution but in our case the generated java script code is dynamic based on some data obtained on the server. Then, the js snippet is emitted to client's browser as (from Webforms snippet):

ClientScript.RegisterStartupScript()

The SSR JS article relies on path to physical java script file. In our case, there's no file, it just plain javascript to be executed once.

Describe the solution you'd like

Provide an similar api for SSR pages to (with a goal to avoid use of a web socket):

ClientScript.RegisterStartupScript()

This api will allow a user to compose a java script string build from some state obtained on the server and execute it on the client once.

A possible solution is to render the java script into some string variable and then inject the JS content into the through a string variable (that contains the JS) inside script block. This would work per/component basis but what about if you want to do it outside the component from some other class that is unaware of the component.

Example:

We have a PageBase class that all our pages derive and sometimes this class needs to emit JS.

I guess I could hack it to use current request context items collection and put the JS code there and then have a component on the page (PageJsInclude) for just the purpose of examining request context items collection, reading it, and rendering it to the page. Sounds hackish but should work. I will give it a try.

Is there any work that is planned in this area to enhance SSR pages to emit JS dynamically? For SSR pages this makes sense in my opinion or is this a bad pattern and then what's the cleaner alternative??

Additional context

No response

htmlsplash avatar Mar 14 '24 19:03 htmlsplash