🟨 Slightly different to Blazor Server
Blazor allows for seamless integration of JavaScript into your applications, making it easy to leverage existing libraries. This tutorial will walk you through the basics of using JavaScript in Blazor, from standard JavaScript to modules, so that you can get started with minimal hassle.
We'll explore the two primary interaction features available for JavaScript integration in Blazor: IJSRuntime
and JSImport/JSExport
. By weighing the pros and cons of each feature, you will be equipped to make an informed decision about which option is the best fit for your project. By the end of this tutorial, you will have a solid understanding of how to incorporate JavaScript into your Blazor applications with confidence.
You can download the example code used in this topic on GitHub.
Blazor is a .NET web framework that allows developers to build web applications using C# instead of JavaScript. Blazor applications run in the browser using WebAssembly, which is a binary instruction format for a stack-based virtual machine that allows code to be executed in the browser. However, there are some scenarios in which it may be necessary or beneficial to use JavaScript in a Blazor project. Here are a few reasons why you might need to use JavaScript in a Blazor project:
mousemove
. In these cases, you can use JavaScript to handle to increase performance or create a custom HTML event.There are 2 ways to implement JavaScript: standard JavaScript and JavaScript module.
The syntax for using standard JavaScript and JavaScript modules is different. For example, standard JavaScript uses global variables and functions, while JavaScript modules use the import
and export
statements to define dependencies and expose functionality between files. In addition, standard JavaScript code is executed in the global scope, while JavaScript modules have their own scope and can be imported and used in other modules.
Blazor offers two built-in features for integrating JavaScript code: IJSRuntime
and JSImport
/JSExport
.
IJSRuntime
is available for both Blazor Server and Blazor WebAssembly and is typically used inside a component. It can also be used to modularize JavaScript code. When using IJSRuntime
, you must control the lifetime of the JavaScript module and its references.
JSImport
/JSExport
is exclusively available for Blazor WebAssembly and is used to modularize JavaScript code. This feature offers more strict control over the data marshalling process by defining the parameters and return types of JavaScript functions as their equivalent C# data types. This prevents unpredictable return data from JavaScript functions. Importantly, using JSImport
/JSExport
eliminates the need to manage the lifetime of the module and its references.
In Blazor Server, the JSImport
/JSExport
is not available.