Run the injected script element once it has been dynamically loaded

When I need to make an AJAX request that injects a script node in either the head or body element, my code looks like this:

window.addEventListener("DOMContentLoaded", () => {

    this._client.get('/getFragment', (responseText) => {
        const obj = JSON.parse(responseText);
        const scriptTag = document.createElement('template');
        scriptTag.innerHTML = obj.fragment;

        document.body.appendChild(scriptTag.content);
    });
});

However, I've encountered an issue where even though the script is injected into the DOM, it doesn't seem to execute because the script itself calls another external URL. When I check the network monitor, I can see that the URL of the script is not being called or executed. How do I ensure that the script tag is actually executed after being injected into the DOM?

The fragment that needs to be injected is as follows:

<script id="mcjs">!function(c,h,i,m,p){m=c.createElement(h),p=c.getElementsByTagName(h)[0],m.async=1,m.src=i,p.parentNode.insertBefore(m,p)}(document,"script","https://chimpstatic.com/mcjs-connected/js/users/1f.js");</script>

Answer №1

It's a bit unclear to me what you're trying to ask, but it seems like the issue lies in creating a template element, which browsers typically do not execute. Have you considered using document.createElement('div') instead?

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

React js: Changing Material-UI functional code to class component results in TypeError

After utilizing the material ui login page code, I discovered that it is a functional component. To meet my specific requirements, I decided to convert it into a class component. However, during the conversion process, an error was encountered: "Cannot ass ...

The scale configuration for scale: x is not valid for creating a time scale chart using chart.js

I am currently utilizing VueJS and attempting to integrate a time scale chart using Chart.js. However, I encountered the following error: Invalid scale configuration for scale: x Below is my configuration : First, I have a component named Chart.vue with ...

What is the best way to incorporate Photoswipe into jQuery Mobile pages?

Trying to incorporate photoswipe into a jquerymobile app is proving to be challenging. The development involves using jquerymobile & Django, and the goal is to set up a gallery on one of the pages. There are three main pages in this setup: the category ind ...

Use React to dynamically render a table by mapping over an array to generate

I'm facing an issue where I am trying to display an array within a specific section of a table, but it's not displaying. Even though all the values are being fetched correctly. const renderReturnReasons = () => { dailyReportDetailItem.re ...

Capture a snapshot with Protractor using the Jasmine2 Screenshot Reporter

The Protractor configuration file includes 2 custom reporting options: one for logging and the other is the protractor-jasmine2-screenshot-reporter. However, only a blank white screen is displayed when generating a screenshot png. Below is the code snippet ...

Is there a way to prevent the window.on('beforeUnload') event from triggering when using the <a> tag?

For my project, I require a user confirmation alert to appear when the user attempts to close the window or tab using the X button. However, the window.on('beforeUnload') function also triggers for hyperlinks. How can I prevent the leave page al ...

The form failed to be submitted even after undergoing ajax validation

Although this question has been asked many times before, I am still confused about where I went wrong. My goal is to validate a form using ajax and submit it if everything checks out. Below is the code snippet that I have been working with: ...

Retrieve the path name of where the user clicked in Next.JS

In a situation where a button is contained in a <Nav/> component shared between two different components, clicking the button triggers the display of a <FileUpload/> component. It is possible to access the <FileUpload/> component from: & ...

Implementing JavaScript to add elements to class

Is there a way to use JavaScript to dynamically add classes to elements? <div class="col-md-4 col-xs-6 work-item web-design" id="SetCategory"> . . <script> document.getElementById("SetCategory").classList.add('{{ $category->nam ...

Dealing with two form submissions using a single handleSubmit function in react-hook-form

I have a React app with two address forms on one page. Each form has its own save address function that stores the address in the database. There is a single submit button that submits both fields and redirects to the next page (The plus button in the circ ...

Using the loop function within HTML in JavaScript with React

I'm trying to loop over my SliderComponent function with different inputs within the HTML to generate multiple components, but I can't seem to get it to work. I came across a solution online that involves building a string and returning it as HTM ...

Phonegap application functioning smoothly on computer, encountering issues on mobile device

Hey there! I recently developed a phonegap app that retrieves JSON data from a YQL link and presents it to the user. It works perfectly on Google Chrome desktop, but my client mentioned that it doesn't work on his Android 2.3 device. Could you help me ...

PHP: Safely Submitting Scores Using JavaScript

I have developed a PHP file that updates scores in a database. For example: http://domain.com/heli/test.php?id=100001181378824&score=50000 The code in test.php is as follows: mysql_connect(localhost,$user,$password); $id = mysql_real_escape_string($_ ...

Preventing the flipping effect with jquery flippy

Hey there! I've been using a cool flippy jquery plugin that I found on this website. It's working great, but I have run into an issue. When the element flips, I want to include a button on the flip side that takes the user to a different page. T ...

Attempting to conceal the select input and footer components of the Calendar component within a React application

I am currently working on customizing a DatePicker component in Antd and my goal is to display only the calendar body. Initially, I attempted to use styled components to specifically target the header and footer of the calendar and apply display: none; st ...

Error: The property 'ss' cannot be accessed because it is undefined

Our main source page will be index.html, while Employees.html is where our results end up. An error occurred: TypeError - Cannot read property 'ss' of undefined Error in the code: let rating = req.body.ss; Seeking assistance please >< C ...

Creating AngularJS variables with dependencies on integer values

Hello, I am a brand new developer and I am currently working on creating an expenses calculator. The goal is to have the sum of inputted integers from a table, each with a default value, become the integer value of another variable. However, I seem to be m ...

PHP implementation for a static header layout

I am interested in learning how to update content without refreshing the header. I have created a simple example below. Header.php <html> <head> </head> <body> <ul> <li><a href="index.php" ...

Using ajax to retrieve data by applying multiple criteria

Currently, I am utilizing AJAX to retrieve database data and compare it with a variable in order to display the information. At the moment, I am only comparing based on one condition in the "Where" clause, specifically whether the field ID is equal to a ...

Insert a value within each iteration of ng-repeat

Is it possible to iterate over a set of items and increment the value of X by 10 each time it is repeated? For example: <rect ng-repeat="a in b" x="0" y="0" fill="#00000" width="206.2" height="117.7" class=" {{ a.name }} " /> I am looking to achie ...