Dynamically Add Script Tag with Src That May Include Document.Write

Dynamically add script tag and execute $(document).ready, without using iframe or document.write

this should work, use it at your own risk:

const styleScriptText =
'<style type="text/css">body {background: #000}</style><script type="text/javascript">alert("OK")</' + 'script' + '>';

const insertStyleScriptText = () => {
const div = document.createElement('div');
div.innerHTML = styleScriptText;
div.childNodes.forEach(child => {
document.head.appendChild(child.cloneNode(true));
if (child.tagName === 'SCRIPT')
eval(child.textContent);
});
};
<button onclick="insertStyleScriptText()">insert StyleScriptText</button>

Dynamically insert script tag?

It seems you are not adding your script tag correctly.
Here is one way you can do it:

 const script = document.createElement("script");
script.type = "text/javascript";
script.src = "";
script.async = true;
script.dataset.cfasync = false;
document.body.appendChild(script);
script.addEventListener("load", () => {
console.log("Script added successfully");
resolve();
});

Dynamically added script tags don't execute

Insert it as an element or self-terminate the tag:

window.onload = function() {  addSources();  console.log(document.body.innerHTML);};

function addSources(){ const selectUserJs = document.querySelector('[src="story_content/user.js"]'); selectUserJs.insertAdjacentElement('afterend',document.createElement('script')).src="../../../modules/speaks/speakDictate.js";
selectUserJs.insertAdjacentHTML('afterend', `<script SRC="../../../modules/speaks/speakDictate.js" TYPE="text/javascript"/>`);}
<script src="story_content/user.js"></script>

Append Dynamic version(variable ) in Script tag and stylesheet based on time

If you are looking for the shortest solution, how about this?

<script>document.write('<link href="/assets/cder.css?v=' + Date.now() + '" rel="stylesheet" />');</script>

A worthy alternative should be:

<script>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/assets/cder.css?v=' + Date.now();
document.body.appendChild(link);
</script>

Well, you must escape the closing script tag as follows:

<script>document.write('<script src="/assets/abc.js?v=' + Date.now() + '"><\/script>');</script>

An example of how to add several scripts:

<script>  var scripts = [    '/assets/abc.js',    '/assets/def.js',  ];
for (var i = 0; i < scripts.length; i++) { var script = document.createElement('script'); script.onerror = function() { alert('Could not load ' + this.src); }; script.src = scripts[i] + '?v=' + Date.now(); document.body.appendChild(script); }</script>


Related Topics



Leave a reply



Submit