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
Remove Multiple DOM Elements
Use a loop to detach elements and then remove them all at once. ``` const elementsToRemove = docum...
Apply Styles to Multiple Elements
Apply a style to multiple elements at once by adding a class. Here highlighting selected list items...