You can inject js script into the document head dynamically like this :
const basicScript = document.createElement('script');
basicScript.type = 'text/javascript';
basicScript.innerHTML = `
console.log('This is a basic script injection.');
`;
document.head.appendChild(basicScript); // append script into head tag
// OR
document.body.appendChild(basicScript); // append script into body tag
I followed this approach to dynamically inject JavaScript scripts into the and <head>
tags via an AJAX call in a cached Laravel application.<body>
This method allows you to dynamically inject and execute a basic script into the document head or body.
You Might Also Like
Dynamically Update Attribute Values
To change the attributes of multiple elements based on user input or other dynamic conditions. Use ~...
Remove Multiple DOM Elements
Use a loop to detach elements and then remove them all at once. ``` const elementsToRemove = docum...