Is there a way to execute a script that has been injected into the page using innerHTML?

Similar Topics:
Executing Scripts inserted with InnerHTML
Inserting Script Tags on Page Load

I have noticed that when using .innerHTML to add script elements like

<script type="text/javascript" src="source.js"></script>

or

<script type="text/javascript"> // embedded code here </script>

The scripts do not execute. They seem inactive or "dead". Is there a way to manually initiate their execution?

Answer №1

To properly add JavaScript to your HTML document, you should place the script inside the head tag like this:

var head = document.getElementsByTagName("head")[0];         
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://www.somedomain.com/somescript.js';
head.appendChild(newScript);

(This is a common practice, and the code snippet was sourced from: )


As a side note: If you are using jQuery, be cautious with appending scripts using the following method:

<script>
    [....]
    $( "head" ).append( "<script src='myScript.js'></script>" ); 
    [....]
</script>

It's important to note that this approach does not work as intended because the JavaScript parser will stop parsing when it encounters the first </script> tag.

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

What is the indicator that signals a change in the value of a React ref.current?

Typically, when using props, we would write componentDidUpdate(oldProps) { if (oldProps.foo !== this.props.foo) { console.log('foo prop changed') } } to identify any changes in props. However, if we utilize React.createRef(), how can w ...

Error encountered while installing Material UI in Next.js with TypeScript and pure JavaScript configurations

I'm brand new to React and Next.js, so please forgive me for asking what may seem like a silly question. I'm attempting to install Material UI in a fresh Next.js application that I created using "npx create-next-app@latest". I've been refere ...

Enhance Material UI with custom properties

Is it possible to add custom props to a Material UI component? I am looking to include additional props beyond what is provided by the API for a specific component. For example, when using Link: https://material-ui.com/api/link/ According to the document ...

Troubleshooting: Custom Plugin's AJAX Functionality Not Functioning as

My latest project involves the development of a plugin that showcases all post types in a drop-down menu, coupled with another select box that displays the relevant categories (taxonomies) for each post type. The aim is to have an AJAX call triggered when ...

Can commands be loaded directly into spec.js files in Cypress instead of support/index.js?

Whenever a new file containing Cypress custom commands is written, it is typically added using Cypress.Commands.add() and then imported into support/index.js. The issue arises when dealing with 100 such Custom command files, as loading all of them every t ...

Merge two arrays together and arrange them in ascending order based on the dateTime field

I have combined two sorted arrays into a new listC. listA = [ {id:"1234435", name:"apple", dateTime_ISO:"2019-01-15 17:27:30"}, {id:"1234435", name:"orange", dateTime_ISO:"2019-01-15 10:25:30"}, {id:"1234435", name:"banana", dateTime_ISO:"2019-01-15 ...

Utilizing my function and the Math.max method to analyze a collection of object data

If I have an array containing objects with hundreds of fields structured like the example below: [ { "designation":"419880 (2011 AH37)", "discovery_date":"2011-01-07T00:00:00.000", "h_mag":19. ...

Obtaining a byte array using the file input method

var profileImage = fileInputInByteArray; $.ajax({ url: 'abc.com/', type: 'POST', dataType: 'json', data: { // Other data ProfileImage: profileimage // Other data }, success: { } }) // Code in Web ...

Astro Project experiencing issues with loading SRC folder and style tags

After setting up a brand new astro repository with the following commands: npm create astro@latest npm run dev I encountered an issue where the default project template failed to display correctly on my computer. Here is how the page appeared: https://i. ...

Check my Twitter feed every 10 seconds

I'm attempting to access my Twitter feed (sent from a smartphone) for a local application, as Twitter is remote... I created a jQuery + JSON script, but with my overly frequent setInterval at 25ms, I quickly hit the limit of 150 requests per hour and ...

Error: Reactjs - Attempting to access the 'name' property of an undefined variable

As I continue to learn about React, I have been experimenting with props in my code. However, I encountered an error where the prop is appearing as undefined. This issue has left me puzzled since I am still at a basic level of understanding React. If anyo ...

Is there a way to prevent Prettier on VS Code from automatically unfolding my code blocks when saving?

I have Prettier set up in my VS Code editor with the formatOnSave feature enabled. However, I am facing an issue where every time I save my (js) or (jsx) file, Prettier automatically expands all my functions. Is there a way to stop this from happening? I ...

`Sending binary data to client through GraphQL: A comprehensive guide`

I have a GraphQL server running on express. I am looking for a way to send images back to the client using nodejs buffer objects instead of JSON. How can I configure my graphql server to return bytes directly, without encoding them in base64 due to large ...

Retrieving the path parameter in a Next.js APIabstractmethod

I need assistance with extracting information from the file routes/api/[slug]/[uid].ts Specifically, I am looking to retrieve the slug and uid within my handler function. Can anyone provide guidance on how to achieve this? ...

The value of a Highcharts series does not match that of a Data Source

Encountering an issue with Highcharts where the value of this.y does not reflect the data source. The discrepancy is apparent in the image below. Uncertain if this is a bug or user error. Screenshot illustrating the problem You can view my Demo here: htt ...

Can you explain the steps to implement this feature in a modal window using jQuery?

My HTML list contains a bunch of li elements. ul li img .det li I am looking to create a modal popup that appears when I click on something. I want this modal popup to have previous and next buttons, preferably implemented using jQuery. I have alr ...

Node.js project that was once functional is now encountering issues with the error message: "Error: Route.post() requires a callback function but received [object Undefined]."

When it comes to asking questions, I typically provide a lot more detail and use specific wording in my titles. However, I'm currently facing an issue that has left me stumped on where to find the solution. Recently, I delved into learning Node JS an ...

Looking to enhance code readability using regular expressions

While I am not a programmer, I enjoy exploring and learning new things. Here is what I have: 1) My URL is structured like this: http://site.com/#!/show/me/stuff/1-12/ 2) I have a jQuery pagination script that displays the number of available pages. Each ...

Guide to navigating to a particular element using PerfectScrollbar

Currently, I am facing a minor challenge while creating my website using the incredible Black Dashboard template for Bootstrap 4. This template, which can be found at (many thanks to Tim for this!), utilizes PerfectScrollbar for jQuery. Although I have ...

Choose an option to modify the URL

I am trying to implement a select form element with values ranging from 1 to 7+. When the user selects "7+", I want the URL to redirect to emailForm.php. How can I achieve this functionality? The other options selected should be captured when the user clic ...