Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute dynamically inserted jquery script after the page has already loaded

Tags:

jquery

ajax

I'm building a page that uses ajax requests to dynamically populate portions of my page.

one of the requests generates an additional jquery script and inserts it into the document. I cannot figure out how to get the newly added jquery script to run after it is inserted into the page... Any ideas as to how to make this work?

like image 487
user2355051 Avatar asked Jun 30 '26 13:06

user2355051


1 Answers

The only way to get scripts to run after the DOM has been parsed, is to add them to the head element:

const scriptText = `...`;
const script = document.createElement(`script`);
script.textContent = scriptText;
document.head.appendChild(script);

or, in jQuery,

const scriptText = `...`;
$(`head`).append($(`<script>${scriptText}</script>`));
like image 187
Mike 'Pomax' Kamermans Avatar answered Jul 02 '26 04:07

Mike 'Pomax' Kamermans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!