user2355051
user2355051

Reputation: 645

Execute dynamically inserted jquery script after the page has already loaded

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?

Upvotes: 3

Views: 2301

Answers (1)

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>`));

Upvotes: 2

Related Questions