'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?



Solution 1:[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>`));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1