2

Usual process to import css / js files from a library to a main project is reference them with

<script src="_content/RazorLib1/hello.js"></script>

But there are some Blazor libraries like DevExpress.Blazor and this one that are able to inject their css / js files without explicit them on main project. What is required to do is call the functions services.AddMyLibrary() and/or services.UseMyLibrary()

How is it possible? I've looked inside Toolbelt.Blazor.LoadingBar library but I didn't find how he reached this behaviour.

2 Answers 2

4

did a blog post for that (German) https://blog.ppedv.de/post/Razor-Classlibrary-JavaScript-einbinden

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. your blog post was useful! If I use your code inside each component of my library I will have a <script> tag for each component loaded with the page. I wrote another JS code to inject inside my component. This code will add a <script> tag if and only if it isn't already inside the page. Can I suggest to edit your code inside jsRuntime.InvokeVoidAsync as I've done as a reply to my question?
1

I solved it thanks to HannesPreishuber's blog post. I suggest following his post changing the js code called inside jsRuntime.InvokeVoidAsync with

(function() {
   let scripts = document.getElementsByTagName("script");
   let exists = false;
   let index = 0;

   while(index < scripts.length && !exists){
       exists = scripts[index].src.endsWith('_content/RazorClassLibrary1/exampleJsInterop.js');
       index++;
   }

   if(!exists) {
       document.body.appendChild(
           Object.assign (
               document.createElement ('script'), {
                   src: '_content/RazorClassLibrary1/exampleJsInterop.js',
                   type: 'text/javascript'
               }));
       }
})()

so the js library will be append once.

1 Comment

IMO when you found a useful post, instead of just commenting under it, you can at least upvote it if it is not the exact answer you were looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.