Javascript: Insert a class declaration post loading of the page

When working with native web components, it is necessary to be able to add class definitions after the page has loaded, especially when new types of components are dynamically added to the DOM.


EDIT: Here's a brief explanation:

In order to define web components, you use a class like this:

customElements.define('my-new-tag', myNewtagClass);
;

Therefore, if you want to introduce a new type of component into the DOM, its corresponding class must be defined. It seems that you cannot programmatically define a global class, as it needs to be defined within the root document/scope.


As of now, the only Pure JavaScript solution I could find is to create the class as a string and insert it using a script in the head of the document.

However, this means having to write the class in this format:

let myClassString = `
class myClass {
  ....
}`;
const sc = document.createElement('script');
sc.setAttribute('type', 'text/javascript');
sc.innerHTML = myClassString;
window.document.head.appendChild(sc);

Unfortunately, this method isn't very practical in most IDEs...

Is there a way to automate this process during the build (considering I use TypeScript and webpack)?

For instance, can I extract the class from a file where it's normally defined and utilize it as a variable elsewhere?

Answer â„–1

I am perplexed by the intention behind creating a class with a string

Below is some code I extracted from my components;
dynamically generating classes/methods/Web Components

<script>
  console.clear();
  const createElement = (tag, props) => Object.assign(document.createElement(tag), props);
  class BaseClass extends HTMLElement {
    constructor(name = null) {
      super();
      this.name = name;
    }
    connectedCallback() {
      this.hello();
    }
  }
  const createClass = (extendFrom, ...args) => {
    class Klass extends extendFrom {
      constructor() {
        super(...args);
      }
    }
    Object.assign(Klass.prototype, {
      ["hello"] : function() {
        this.innerHTML = `Hello from <b>${this.name}!</b><br>`;
      }    
    });
    return Klass
  }
  const createComponent = (name, defaultClass = BaseClass) => {
    customElements.define(name, createClass(defaultClass, name));
    document.body.append(createElement(name, {
      title: name,
    }))
  }
  document.onclick = () => {
    let count = document.body.querySelectorAll("[title]").length + 1;
    createComponent("new-component" + count);
  }
  createComponent("my-comp1");
  createComponent("my-comp2");
</script>
click document!<br>

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

Ignoring CSS transitions by changing the width property in JavaScript’s element.style

When attempting to create a smooth progress bar animation by adjusting the width using document.querySelector('#mydiv').style.width = '20%', I noticed that the new width is updated instantly rather than transitioning smoothly. It seems ...

I am unable to halt the relentless stream of asynchronous events

Struggling to retrieve an array using a loop in the asynchronous environment of nodejs. Check out my code below: getDevices(userIDs, function(result) { if (result) { sendNotification(messageUser, messageText, result); res.send("Success"); } else { ...

Servlet question: What causes the XMLHttpRequest responseText to consistently appear empty?

I've been going crazy trying to figure out how to solve this issue. I have a servlet deployed in Tomcat running on localhost:8080 that looks like this: @WebServlet(urlPatterns = { "/createcon" }, asyncSupported = true) public class CreateCon extends ...

Error: AppModule requires an array of arguments in order to function properly

Upon successfully compiling my Angular application and running ng serve, I encountered the following error in the browser console. AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: Arguments array must have arguments. at injectArgs (core.js:1412) at c ...

Encountering EAGAIN error while running npm install within a Jenkins build process alongside Maven

My Jenkins pipeline is set up for an application that uses Spring Boot as the backend and Vue.js as the frontend. The Maven build process builds the frontend first, copies it to the backend, and then builds the backend. However, during the frontend build, ...

Loop through the JSON data and dynamically display corresponding HTML code based on the data

I've developed a survey application using React, where I initially wrote code for each question to display radio buttons/inputs for answers. However, as the survey grew with multiple questions, this approach resulted in lengthy and repetitive code. To ...

Utilize AJAX to retrieve the output of a PHP randomizer

Current situation: I have a PHP file with a randomizer function and HTML that utilizes this function to display strings from a separate text document. The Function: <?php function rand_line($fileName, $maxLineLength = 4096) { $handle = @fopen($fileN ...

I am looking to modify the appearance of specific sections of a searched word in React.js, such as making them bold or lighter. Can anyone

After coming across several similar questions, I realized none quite matched my issue. Specifically, I am attempting to style only the part of the search result that relates to the entered query. For instance, if the query is "Thi", I want the result to di ...

Tips for confirming that one of three checkboxes has been selected in AngularJS

Here is the code snippet for checkboxes: <input name="chkbx1" type="checkbox" ng-model="LoanReferData.Prop1" ng-class="Submitted?'ng-dirty':''" required>Prop 1</input> <input name="chkbx2" type="checkbox" ng ...

What is the best way to access an Ajax response outside of its function using JQuery?

Just starting out with JQuery and wondering how to utilize the Ajax response ( HTTP GET ) outside of the function in my code snippet below: $.ajax ({ type: "GET", url: "/api", success: success, error: error ...

Having trouble receiving the response from PHP after making an AJAX request

Can you help me figure out why I'm not receiving any return value from the ajax data post? Take a look at my code and let me know where I might be going wrong. Here is a snippet of my jQuery code: $("#btnlogin").click(function(){ var email = $( ...

Extract information from JSON using a filter

Is there a way to extract the data value from the list without relying on index positions, considering that the order of arrays can change? I need to specifically target data where code === "size". Unfortunately, the existing structure cannot be ...

How can I gather information from members who have already signed up?

I have a form that submits data to the Angular Firebase database. Once the form is submitted, I want to display the previously submitted data in the form if the user signs in again. Below is my .ts file: import { Component, OnInit } from '@angular/c ...

What strategies can be implemented to minimize the use of if-else statements?

Is there a more efficient way to simplify this if-else statement? This code dynamically changes the picture based on integers retrieved from the database. I am looking for ways to optimize this code. if (val["soil_h"] < 21){ $("#ground").att ...

Problem with Java class in GWT JsInterop

Having some trouble with JsInterop while wrapping up a piece of JavaScript code. The JavaScript code looks like this: com = { gwidgets: {} }; com.gwidgets.Spring = function () { this.name = "hello"; }; com.gwidgets.Spring.prototype.getName = ...

Vue's v-for loop updates all input fields instead of just one, ensuring consistency across the board

After spending hours on this issue, I am still stuck and unable to find a solution through Google search. The problem lies in my v-for loop where I am iterating over an array of objects. Each iteration renders input fields displaying the name and price of ...

What are the steps to accessing validation errors using express-validator?

Recently, I delved into the world of express-validator to enhance my skills. Despite going through the documentation thoroughly, there's a query lingering in my mind that might have already been addressed in the docs. My confusion arises from needing ...

Addressing the issue of Google Charts legends overlapping

As a newcomer to Stackoverflow and Google Charts, I am encountering an issue in one of my projects that utilizes the Google Charts API. Specifically, I am trying to display two legends on the chart but they are overlapping in the preview. Despite explorin ...

What is the solution to adding values from a counter?

I am trying to create a JavaScript counter: function animateSun() { var $elie = $("#sun"); $({ degree: 0 }).animate({ degree: 360 }, { duration: 190999, easing: 'linear', step: function(val) { now = Math.round ...

JQuery .click function functioning properly on alternate clicks

Currently, I am integrating JQuery with ReactJS. However, there seems to be an issue where the action that should occur when clicking a button only works on every other click. The first click doesn't trigger anything, but the second one does. I attem ...