1
votes

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

2 Answers

1
votes

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.