Exploring the Power of Webpack and Web Workers within Ionic 2

In our upcoming Ionic 2 project, we are considering the implementation of web workers. However, due to the usage of ionic-app-scripts (version 1.0.0) with webpack in Ionic 2 (https://github.com/ionic-team/ionic-app-scripts), we face the challenge of having a web worker TypeScript file that needs to be compiled separately from other files and not bundled with main.js.

Our plan involves naming the file as servicetest.worker.ts, where the ".worker" extension would signify that it should be compiled from TypeScript to JavaScript independently without bundling.

We welcome any advice on this matter as it appears that customization of app scripts might be required.

Answer №1

Although this answer is coming in a little late, it might be beneficial to someone else in need. Check out

I followed the instructions from the mentioned article but had to tweak them slightly as I needed to call a worker method on demand instead of during instantiation.

In the ./src/assets directory, create a new folder named 'workers' where your worker files with a .js extension will reside. TypeScript files may not compile into usable web workers.

Create a web worker. Below is an excerpt from my fuzzySearch web worker's main code (

./assets/workers/fuzzysearch-worker.js
):

'use strict';

var pattern, originalList;
self.onmessage = function(event) {
    // Responding to received messages
    pattern = event.data.pattern;
    originalList = event.data.originalList;
    self.doFuzzySearch();
};

self.doFuzzySearch = function() {
    var filteredList;

    console.time('internalFastFilter');
    filteredList = self.fastFilter(originalList, (item) => self.hasApproxPattern(item.searchField, pattern));
    console.timeEnd('internalFastFilter');

    // Sending back the results 
    postMessage({ filteredList: filteredList });    
};

// The code above intentionally left incomplete

In your .ts file, declare the worker variable (usually above the constructor):

private readonly searchWorker: Worker = new Worker('./assets/workers/fuzzysearch-worker.js');

In the constructor:

constructor(/* Other injected dependencies here */
    public ngZone: NgZone) {       

        this.searchWorker.onmessage = (event) => {
          // Inside ngZone for proper ChangeDetection
          this.ngZone.run(()=> {                        
            this.dataList = event.data.filteredList;
            console.timeEnd('searchWorker');
          })
        };        

  }

Lastly, in your "action function", let's say doSearch:

doSearch(event) {
    // ... additional code to perform some operations

    console.time('searchWorker');
    this.searchWorker.postMessage({ command: 'doFuzzySearch', originalList: this.realList, pattern: searchFilter });

    // ... additional code to do more operations
}

this.searchWorker.postMessage initiates the call. All intensive processing tasks are handled within the web worker.

Hope this provides assistance. Warm regards.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Execute the "organizeImports" trigger through the terminal in TypeScript

One feature of VSCode is its editor capability to organize and clean imports in javascript and typescript files upon saving ( "source.organizeImports": true ). Inquiry Is there a way to trigger this action on a file using the command line? Something alo ...

Editing the app.js file can cause it to malfunction and stop working

As I work on designing a webpage for a construction company using a template, I face an issue with the js file named app.js. Whenever I make edits to the script, the entire HTML page loses its responsiveness as if the js file was never included in the firs ...

Finding the element in the HTML using selenium and Python

Recently, I have been working on automated testing using Selenium. However, I have encountered a strange issue where I am unable to locate the element. Can someone please provide me with guidance on how to handle this situation? driver.find_element_by_xpa ...

Modifying Image on Tab Click using jQuery

In my current WordPress project, I am working on dynamically changing an image based on the tab that is clicked. I would like to use jQuery's fade effect to smoothly replace the image with a new one that is relative to the specific tab being clicked. ...

Ways to showcase an array within another array using VueJS

I encountered an issue with an API call that returns its result as an array within an array. Each nested array contains card transactions that need to be displayed. Upon examining the console output, I found: Array [ Object { "data": Array ...

What methods does JUMflot use to update points or select items? Interested in adding objects to an array and redrawing them without altering the original item

My goal is to use a button to push a line into an array and have JUMflot redraw those lines without affecting the original line being pushed in. Initially, I attempted this using the following code snippet (the generator ID represents the button and optio ...

Extending an interface in TypeScript to include an Array

Can I implement a parent interface in Angular 4? export interface Devices extends Array<Device> { } The error 'Class 'DevicesModel' incorrectly implements interface 'Devices'. Property 'includes' is missing in typ ...

How can I fill a FormArray within a Mat Table?

I've been attempting to construct a material table using FormArray, but I've encountered an issue with the formContolName not being set. Here is the code snippet I've put together: TS form = this.fb.group({ production: this.fb.array([this ...

I can't figure out why I keep receiving an "Uncaught ReferenceError: THREE is not defined" message from three.js, especially after I made sure to include a requirejs shim

My code is throwing an error that says: Uncaught ReferenceError: THREE is not defined module game { export class Add3DScene extends dragonwings.Command { @inject('ResponsiveDiv') protected _responsiveDiv: components.Res ...

Synchronously executing Twitter posts

Hello there! I've been using this code found here to embed Twitter posts on my website. It's been working perfectly on certain pages, like in the forums, but I've run into an issue while browsing through user profiles. The post history for e ...

The hover state of a div will not be lost if its parent element is not being hovered over

When hovering over the second, third, or fourth item, hidden text will appear on the left side. If you hover your cursor over the hidden text, it will disappear again. I want to be able to hover over the second item, move my cursor to "hide", and click o ...

What is causing the code behind to reject the href with 'aspx' in the anchor tag?

I am currently working on implementing a calendar control that will display Today's Due and Overdue items in separate accordion sections when a date is selected. To achieve this, I have written the necessary code in the back end and used a style.css f ...

Combining strings with objects in Javascript: A step-by-step guide

In the code snippet provided, I am combining variables to create a path to another existing object and its attribute. The issue is that I always receive a string, but I would like to somehow convert it into an object. // SET CUSTOM CONTENT FOR COLUMN IF ...

React and Enzyme are coming up empty-handed when trying to locate any elements within a functional component

After creating a simple functional component in React with Typescript, I encountered an issue while testing it. Every time I try to gather the divs, I keep receiving an empty object {}. Here is how the component is structured: export const TestComponent ...

Waiting for a response from an API with the help of nodejs

I'm new to exploring Node.js and I'm interested in making API calls where the result is awaited before proceeding with any further actions. // defining endpoint function function getListMarket() { var deferred = Q.defer(); deferred.resolve(Q ...

Avoid positioning issues when dropping a DIV onto the Canvas

Utilizing the JavaScript code below allows me to drag a DIV onto a canvas. I am currently loading a multi-page PDF, which consists of image files, in a pop-up window and positioning canvas layers over them. In these canvas layers, shapes are then loaded at ...

A guide on selectively removing a value from a javascript object when calling setState in ReactJS

updateDishDetails(id, quantity) { if (quantity !== 0) { this.setState( prevState => ({ bookingFormData: { ...prevState.bookingFormData, dishDetails: { ...prevState.bookingFormData.dishDe ...

In Vue, using the ref function does not automatically result in the creation of a

CustomPage.vue: <template> <div> <CustomChild :cat = "this.parentCat" /> <div v-on:click="this.changeName" id="change-button"> Change Parent Cat name </div> </div> ...

Reactjs: When components are reused, conflicts may arise in UI changes

I'm currently working on creating a sample chat room application using reactjs and redux for educational purposes. In this scenario, there will be 3 users and the Message_01 component will be reused 3 times. Below is the code snippet: const Main = Re ...

Determining the successful completion of an ajax request using jQuery editable plugin

I recently started using Jeditable to enable inline editing on my website. $(".video_content_right .project_description").editable(BASE_URL+"/update/description", { indicator: "<img src='" + BASE_URL + "/resources/assets/front/images/indicator ...