#JSRuntime
Explore tagged Tumblr posts
Text
JavaScript Engines Unveiled: Enhancing Web Performance | FloatChat
Introduction
At FloatChat, we are passionate about cutting-edge technologies that enhance web experiences. As a leading tech company, we understand the crucial role JavaScript engines play in web development today.
JavaScript started off as a simple scripting language to add minor interactivity to web pages. But over the years it has evolved into a powerful platform running complex web applications. JavaScript engines are at the heart of this transformation. They allow JavaScript code to run faster while using fewer resources.
In this blog post, we aim to provide you with an in-depth understanding of JavaScript engines. We will learn:
What JavaScript engines are and how they work
Explore popular engines like V8, SpiderMonkey, and Chakra
Optimization techniques to improve JavaScript performance
Emerging trends and the future of JavaScript engines
Real-world examples of engines powering interactivity
FloatChat's contributions to advancing web technology
Equipped with this comprehensive guide, you will be able to leverage the full potential of JavaScript for building interactive web experiences.
What Is a JavaScript Engine?
A JavaScript engine is a program that interprets and executes JavaScript code. The engine reads through the code, converts it into machine-readable instructions, and runs those instructions.
JavaScript serves as the engine that powers dynamic behavior and interactivity on websites. It allows developers to implement features like:
Dynamic updating of content
Animations and visual effects
Real-time validation of forms
Interactive charts and graphs
2D/3D gaming experiences
JavaScript engines are built into web browsers to parse and run JavaScript code contained within web pages. Some common web browsers that use JavaScript engines include:
Google Chrome (V8 engine)
Mozilla Firefox (SpiderMonkey engine)
Safari (JavaScriptCore engine)
Microsoft Edge (Chakra engine)
These browsers rely on their respective JavaScript engines to render pages and handle JavaScript code. The performance of the engine impacts how fast and responsive a web page is.
How JavaScript Engines Work
JavaScript engines use a number of steps to execute code:
Parsing: First, the engine parses the JavaScript code into a tree-like structure called the Abstract Syntax Tree (AST). This breaks down the code into meaningful chunks.
Compilation: The parsed code gets compiled into machine code that the computer processor understands.
Profiling: The engine determines hot functions that get called frequently.
Optimization: Hot functions are further optimized using techniques like inline caching.
Execution: The optimized machine code finally gets executed to run the JavaScript program.
JavaScript engines contain a compiler that does many performance optimizations like just-in-time (JIT) compilation. This compiles JavaScript to machine code at runtime, right before execution.
Google's V8 engine spearheaded many of these optimization techniques. Some key principles behind its design include:
Using hidden classes for object representations
Dynamic machine code generation
Efficient garbage collection
Caching optimized code
These advances delivered huge performance gains over earlier JavaScript engines, paving the way for complex web applications.
Key JavaScript Engines
Let's explore the most prominent JavaScript engines powering interactivity on the web:
V8 Engine
The open-source V8 engine by Google powers Google Chrome and Node.js. It is written in C++.
Key features of V8:
JIT compilation increases execution speed
Uses inline caching to optimize hot functions
Fast object representation using hidden classes
Garbage collection efficiently frees up memory
Code minification and other compiler optimizations
Google continues to advance V8 to offer greater performance with new EcmaScript standards and features.
SpiderMonkey Engine
SpiderMonkey is the original JavaScript engine developed by Brendan Eich at Netscape in 1994. It is used in Mozilla Firefox and written in C/C++.
Features of SpiderMonkey:
Just-in-time compilation for faster code execution
Advanced garbage collection and memory management
Support for concurrency and multi-core processors
Extensible using JavaScript APIs and C interfaces
SpiderMonkey utilizes the compiler technology present in Firefox to deliver high performance.
JavaScriptCore Engine
JavaScriptCore is WebKit's JavaScript engine used in Apple's Safari browser. It implements the ECMAScript specification using multiple optimization techniques.
Some optimizations in JavaScriptCore:
Inline caching of properties
Polymorphic inline caches to optimize objects based on types
LLInt and baseline JIT compiler to optimize hot paths
FTL JIT compiler to optimize across function boundaries
Apple contributes to improving JavaScriptCore as part of the open-source WebKit project.
Chakra Engine
The Chakra engine by Microsoft powers Microsoft Edge and other Microsoft applications. It combines JIT compilation with profilingguided optimizations.
Some notable aspects of Chakra:
Background JIT compilation doesn't block execution
Adaptive optimizations based on runtime profiling
Advanced memory management and garbage collection
Support for concurrency and multi-threaded execution
Microsoft actively develops Chakra as part of its ChakraCore open source project.
Optimizing JavaScript Performance
While JavaScript engines handle compilation and execution, developers also need to write optimized code for best performance. Here are some key optimization techniques:
Minification: Removing whitespace, comments, and non-essential code to reduce file size. Tools like UglifyJS automate the minification process.
Bundling: Combining multiple JavaScript files into a single bundled file to reduce HTTP requests. Webpack, Rollup.js and Parcel are useful bundling tools.
Cached API calls: Caching values from API calls to avoid redundant requests. Useful for rate-limited APIs.
Asynchronous loading: Loading non-critical resources asynchronously to avoid blocking page rendering. Solutions like Async.js simplify asynchronous flows.
Tree shaking: Removing unused code to streamline production code. Bundlers like Rollup.js support tree shaking.
Lazy loading: Dynamically loading non-essential modules at runtime to boost initial load time. Libraries like dynamic-import-polyfill enable lazy loading.
Ahead-of-Time compilation: Pre-compiling JavaScript to machine code during build time for faster startup. Tools like Vite support this technique.
JavaScript engines also continue to introduce performance optimizations over time, further improving web experiences built with JavaScript.
Key improvements along the way include:
Faster compilation using just-in-time and ahead-of-time techniques
Runtime optimizations through profiling and caching
More efficient memory management and garbage collection
Support for concurrency and parallel execution
Adherence to evolving JavaScript standards
JavaScript engines will continue to adapt and leverage emerging hardware improvements for faster execution with lower overhead.
Challenges and Future Trends
Despite massive progress, JavaScript engines continue to face challenges:
Performance limitations: Large JavaScript codebases can suffer slow startup and execution compared to native apps. Engines are limited by web runtime constraints.
Memory consumption: Complex apps with huge codebases can consume excessive memory which engines must efficiently manage.
Security vulnerabilities: Code execution capabilities create potential for cross-site scripting and injection attacks. Engines aim to provide security sandboxes.
Standards support: Keeping up with the rapid evolution of JavaScript and web platform standards.
Emerging trends: Adapting to trends like WebAssembly which allows other languages to run via the browser.
To address these challenges, upcoming trends for JavaScript engines include:
Continued performance optimizations and improved memory management.
Increased adoption of WebAssembly to complement existing JavaScript capabilities.
Stronger security features and isolation mechanisms.
Support for new EcmaScript standards and proposals.
Expanding browser compatibility and cross-platform reach.
JavaScript Engines in Action
JavaScript engines power interactive experiences across many industries:
Web Applications: Complex apps like Google Docs, Trello, and Slack running fully in the browser.
Gaming: Graphics/physics-heavy games like Minecraft in browsers via engines like PlayCanvas.
Data Visualization: Interactive charts/graphs in finance, healthcare, and scientific data analysis.
Digital Advertising: Rich multimedia ads created using JavaScript frameworks.
E-commerce: Dynamic interfaces for online shopping with live previews and updates.
Web Accessibility: JavaScript assists features like screen readers and braille displays.
JavaScript engine performance is crucial for these apps to deliver seamless user experiences. Faster engines directly translate to higher engagement and revenue.
FloatChat's Contribution to JavaScript Engine Advancements
At FloatChat, our teams continuously experiment with new JavaScript engines and platform capabilities.
We collaborate with industry partners like Google and Mozilla to push the envelope on JavaScript performance and APIs. Our real-world findings and data directly contribute to optimizing these rapidly evolving engines.
FloatChat also participates in shaping web standards by providing feedback on JavaScript features and proposing new APIs to empower developers.
We are committed to driving technology advancements that create more interactive, engaging web experiences. JavaScript engines are a key part of this mission.
Conclusion
JavaScript engines have revolutionized our ability to build highly interactive web applications. Their techniques like just-in-time compilation, caching, and concurrency allow JavaScript code to run much faster than interpreted languages.
Modern engines like V8 and SpiderMonkey use an array of optimizations to provide a massive performance boost over early versions. With continued evolution, they are bridging the gap between native and web applications.
While engines still face challenges with memory, performance, and security, upcoming trends promise to address these limitations. The future is bright for JavaScript to power even more sophisticated experiences powered by versatile engines.
We hope this guide gave you valuable insights into the inner workings of JavaScript engines. Leverage these advancements to create lightning-fast, interactive applications that users will love.
To learn more about using JavaScript for advanced web development, be sure to explore FloatChat's tech blog and resource library. Our team will be happy to discuss how we can collaborate to push web technology forward.
#JavaScriptEngine#JSRuntime#JavaScriptPerformance#WebDevelopment#Programming#CodeOptimization#TechTalk#WebEngine#JavaScriptOptimization#FloatChat
0 notes
Text
JSruntime play sound on mobile blazor is not working for certain phone. Eventually, I drop to continue it. I change to study other method, and finally get a very good solution as below code: Xamarin.Essentials.TextToSpeech.SpeakAsync(totext).ContinueWith((t) => { }, TaskScheduler.FromCurrentSynchronizationContext());
0 notes
Text
I took a lot time to fix the mobile blazor play sound.
Until now still duno why it cannot play audio from wwwroot folder, at the end i try point to external.
Having issue on timer event calling asyn jsruntime issue too, it is not stable, i have to run the jsruntime on intialize function then it is only able to play sound at timer event.
0 notes
Text
Mobile blazor 0.4 preview does not support jsruntime so I try to create new set of 0.5 preview project and copy all the code to it. The bad path is the image refer path method was changed in 0.5 preview, this cause me waste a lot of time to find out what is the correct path.
0 notes
Text
Write a reusable Blazor component
In this blog I have already talked about creating components but now I want to start from the beginning and explain how to write a reusable Blazor component from scratch. This is the first part of a Blazor article series to tell how to create a reusable Blazor component. So, we can use them in our Blazor application independently of the hosting model (Web Assembly or Server-side). If you google a bit, you can find a lot of example like that but I can’t find one example that explain exactly how the interaction works. Here, step by step what I understood.
Then, for more documentation, example and components about Blazor, here same links in this blog:
Getting Started With C# And Blazor
Setting Up A Blazor WebAssembly Application
Working With Blazor’s Component Model
Secure Blazor WebAssembly With IdentityServer4
Blazor Using HttpClient With Authentication
InputSelect component for enumerations in Blazor
Use LocalStorage with Blazor WebAssembly
Modal Dialog component for Blazor
Create Tooltip component for Blazor
Consume ASP.NET Core Razor components from Razor class libraries | Microsoft Docs
Also, you can download the source code of this post from GitHub.
So, there result of this post is a simple button. When you click the button, Blazor calls the code in a javascript file and runs it. The result is passed to the C# code and then as result of the component.
Start!
First, I have to create a new Blazor project. For that, Create a new project and search for Blazor. Then, select Blazor WebAssembly App.
Visual Studio 2019 – Create a new project
Then, you have to select the name of the project and its location. The name of my project is PSCBlazor and you can find it on GitHub.
Configure a new project
Select as Target Framework .NET 5. Then, Create.
Addition Information
Now, we have the main project. But to write a reusable Blazor component, we have to create another project for it. Following the same procedure, create a new project but this time select Razor Class Library.
Create a Razor Class Library
Then, follow the instruction. The name of my project is PSCBlazor.SimpleComponent.
If you don’t want to use Visual Studio, you can run from the Command Line
dotnet new razorclasslib
By default, the created project contains several elements:
A predefined “Component1” that is a basic component displaying some styled text in Component1.razor.
A ExampleJsInterop class that demonstrate how to call a basic JS function defined in its own js file in ExampleJsInterop.cs.
The static resources (like png, css and js files) in the “wwwroot” folder: – background.png – exampleJsInterop.js – styles.css
The solution for the custom component
Separate the code from the razor code
Behind the scenes, when you write a razor page, an actual C# class is generated and hopefully the class is partial. It means that it is easy to separate the behavioral code of your component from the html view code.
Single mixed file Component1.razor:
<div class="my-component"> This Blazor component is defined in the <strong>PSCBlazor.SimpleComponent</strong> package. </div> @code { }
Sometimes it is nice to separate the view from the code. In Visual Studio is pretty simple. Create a new Class with the full name of the view file plus cs. For example, if the view is Component1.razor the new file should be Component.razor.cs and automatically Visual Studio understands that this file is part of the view.
Split view and code
Then, a little change in the code because the new class must be a partial class. For example:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSCBlazor.SimpleComponent { public partial class Component1 { } }
Interop between Blazor and JavaScript
Now, I write a reusable component for Blazor and I’m going to modify the component to be able to exchange some data between the component itself and the parent. For that, I have to use a JS function through the generated ExampleJsInterop to prompt the user for a text input.
The component will be used this way with TextValue being a property used in the binding:
<Component1 ParentName=”Some text I want to transmit from the parent to the child component” @bind-Text=”TextValue”> </Component1>
Define the parameters
We need to define a property ParentName to transmit some data from the parent to the child component:
[Parameter] public string ParentName { get; set; }
The Parameter attribute tells that the C# property can be used as component parameter.
Now, I need to define a parameter to be able to transmit data to the child component, but we also want to get data from the component using a @bind property.
To make it possible, I have to define a parameter like the previous one named in our case Text.
[Parameter] public string Text { get; set; }
Define a EventCallback parameter to be able to notify the binding engine that the value has changed. As a convention, the name of the event callback property must be named accordingly to the property you want to bind. In our case it must be named TextChanged.
[Parameter] public EventCallback<string> TextChanged { get; set; }
The name of the event callback can be named differently but in that case it is required to specify it when binding a value using
@bind-{Property}:event=”NameOfPropertyChanged”
It means that the two notation are equivalent when binding a value:
<Child @bind-MyProperty="Text" /> <Child @bind-MyProperty="Text" @bind-MyProperty:event="TextChanged" />
Once the properties are defined, the component will have to invoke the event callback when the property value is changing.
await TextChanged.InvokeAsync(valueOfUserTextInputFromModalDialog);
Inject the appropriate services
To use the Java Script interop and the ExampleJsInterop example class we have to use an injected instance of IJSRuntime. We can do it with a dedicated attribute Inject in the component C# file.
Implement the behavior
Now, I have all we need to implement the behavior by adding a button with a click handler that is going to call the JS function through the ExampleJsInterop.Prompt method. Once we got the result we just need to forward to the TextChanged event call back and to update our Text property value.
So, in the razor file I created a bit of HTML, just to have a bit more fun.
<div class="my-component"> <div class="my-buttonkeeper"> <button class="my-button" @onclick="GetTextAsync">Click me</button> </div> </div> <br /> <text>Text (in the component) : @Text</text> <br />
Then, in the Component1.razor.css I added some CSS code
.my-component { border: 2px dashed red; padding: 1em; margin: 1em 0; background-image: url('background.png'); } .my-buttonkeeper { text-align: center; } .my-button { width: 150px; height: 150px; background-color: green; color: white; font-size: 20px; }
Why? Because I want to be sure the main application adds the CSS from this component but also the javascript we need. I’ll explain that in a second.
Then, it is the moment of the CS file:
private async Task GetTextAsync() { // Call JS interop. var text = await new ExampleJsInterop(JsRuntime).Prompt("Enter some text:"); // Trigger the changed event. await TextChanged.InvokeAsync(text); // Set the property value. Text = text; }
Inside wwwroot directory we have ready to use exampleJsInterop.js file which was created by Visual Studio or CLI. The code is like that
// This is a JavaScript module that is loaded on demand. It can export any number of // functions, and may import other JavaScript modules if required. export function showPrompt(message) { return prompt(message, 'Type anything here'); }
This is a simple javascript function. This rings a bell to me, it is like in React. Now, the magic is happening in the ExampleJsInterop.cs
using Microsoft.JSInterop; using System; using System.Threading.Tasks; namespace PSCBlazor.SimpleComponent { // This class provides an example of how JavaScript functionality can be wrapped // in a .NET class for easy consumption. The associated JavaScript module is // loaded on demand when first needed. // // This class can be registered as scoped DI service and then injected into Blazor // components for use. public class ExampleJsInterop : IAsyncDisposable { private readonly Lazy<Task<IJSObjectReference>> moduleTask; public ExampleJsInterop(IJSRuntime jsRuntime) { moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>( "import", "./_content/PSCBlazor.SimpleComponent/exampleJsInterop.js").AsTask()); } public async ValueTask<string> Prompt(string message) { var module = await moduleTask.Value; return await module.InvokeAsync<string>("showPrompt", message); } public async ValueTask DisposeAsync() { if (moduleTask.IsValueCreated) { var module = await moduleTask.Value; await module.DisposeAsync(); } } } }
So, between the lines 24 and 28 there is a call via IJSObjectReference to the javascript function in the file under the wwwroot. You can see that in line 21 where there is an import of the javascript file.
Run the demo project
So, almost finish to write a reusable Blazor component with interop with javascript. First, I have to add the component as dependency in the project. In Solution Explorer, right click on Dependecies in the PSCBlazor and click on Add project references… Then, select the component.
Reference manager
Now, open _Imports.razor and add the reference to this component to add this line
@using PSCBlazor.SimpleComponent
Then, open Index.razor and add this code
<Component1 ParentName="This is a test" @bind-Text="_text"></Component1> The text from the component is: @_text @code { private string _text = ""; }
Also, we want to add the CSS and the javascript for the magic. Depending on the hosting model, it is required to add the reference to the CSS and javascript in specific index files in the application project:
wwwroot/index.html for the Web Assembly hosting model.
and
Pages/_Host.cshtml for the Server-side hosting model.
So, open the index.html under wwwroot and add those lines (I deleted a lot of lines for the purpose of showing what you have to add):
<head> <link href="_content/PSCBlazor.SimpleComponent/styles.css" rel="stylesheet" /> </head> <body> <script src="_framework/blazor.webassembly.js"></script> <script src="_content/PSCBlazor.SimpleComponent/exampleJsInterop.js" /> </body>
Basically, in the head I have to add the reference to the CSS from the component. Similarly, I have to do the same to add the javascript.
Compile and run. If everything is ok, you have the same result as I show at the top of this post.
The post Write a reusable Blazor component appeared first on PureSourceCode.
from WordPress https://www.puresourcecode.com/dotnet/blazor/write-a-reusable-blazor-component/
0 notes