How to Execute a Dynamically Loaded JavaScript Block

How do you execute a dynamically loaded JavaScript block?

Script added by setting the innerHTML property of an element doesn't get executed. Try creating a new div, setting its innerHTML, then adding this new div to the DOM. For example:


<html>
<head>
<script type='text/javascript'>
function addScript()
{
var str = "<script>alert('i am here');<\/script>";
var newdiv = document.createElement('div');
newdiv.innerHTML = str;
document.getElementById('target').appendChild(newdiv);
}
</script>
</head>
<body>
<input type="button" value="add script" onclick="addScript()"/>
<div>hello world</div>
<div id="target"></div>
</body>
</html>

How to dynamically load and use/call a JavaScript file?

You could do it like this:

function loadjs(file) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = file;
script.onload = function(){
alert("Script is ready!");
console.log(test.defult_id);
};
document.body.appendChild(script);
}

For more information read this article : https://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/

Javascript not firing with dynamically loaded form and scripts

Here's how I solved it for anyone else with this problem.

It wasn't a loading problem. All the scripts and HTML loaded fine. The problem was that one of the dynamically loaded scripts listing.js had a document.ready() wrapper which wasn't firing since DOM was already loaded, so JS elements on the dynamically-loaded form weren't being initialized. However, when I removed the document.ready(), it still wasn't initializing the dynamically-loaded elements.

To get around this, I changed the document.ready() to a function initialize() and called that last from the dynamically-loaded HTML. It all works fine now:

//DYNAMICALLY LOADED SCRIPT FIRST    
function initialize(){

//INITIALIZE JS FORM ELEMENTS...

}

Then, in the same AJAX call:

<form class="dynamically-loaded-HTML">

<!-- FORM ELEMENTS -->

</form>
<script>
initialize();
</script>

Dynamically load a JavaScript file

You may create a script element dynamically, using Prototypes:

new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});

The problem here is that we do not know when the external script file is fully loaded.

We often want our dependant code on the very next line and like to write something like:

if (iNeedSomeMore) {
Script.load("myBigCodeLibrary.js"); // includes code for myFancyMethod();
myFancyMethod(); // cool, no need for callbacks!
}

There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a synchronous AJAX request and eval the script on global level.

If you use Prototype the Script.load method looks like this:

var Script = {
_loadedScripts: [],
include: function(script) {
// include script only once
if (this._loadedScripts.include(script)) {
return false;
}
// request file synchronous
var code = new Ajax.Request(script, {
asynchronous: false,
method: "GET",
evalJS: false,
evalJSON: false
}).transport.responseText;
// eval code on global level
if (Prototype.Browser.IE) {
window.execScript(code);
} else if (Prototype.Browser.WebKit) {
$$("head").first().insert(Object.extend(
new Element("script", {
type: "text/javascript"
}), {
text: code
}
));
} else {
window.eval(code);
}
// remember included script
this._loadedScripts.push(script);
}
};

Call Function from Dynamically loaded Javascript file

Consider reading more about Promises
https://developer.mozilla.org/he/docs/Web/JavaScript/Reference/Global_Objects/Promise

the following is an example using your code,
I don't think it fully do what you're looking for (as I called the loadFunction in the editor.js and not in the main file, but I believe this example + the documentation above will help you get the idea). Good luck :)

base.js

let loadFunction = function (type) {
//loading localization script
let script = document.createElement('script');
script.type = 'text/javascript';
document.querySelector('body').appendChild(script );
if(type == "multiply")
script.src = `script1.js`
else
script.src = `script2.js`

// return a promise
return new Promise((res, rej) => {
script.onload = function() {
res();
}
script.onerror = function () {
rej();
}
});
}

editor.js

loadFunction('multiple')
.then(() => {
// The script file has been loaded.
// We can use the function.
var result = Calculate(5,9);
console.log(result);
})
.catch(() => {
console.error('Could not load the script file.');
});
  • Haven't fully tested the code.

Javascript | dynamically loaded script but unable to read/use variables in file right after

I would make like that:

<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script>
let scriptEle = document.createElement("script");
scriptEle.async = false;
scriptEle.defer = true;
scriptEle.setAttribute("src", "./t.js");
document.head.appendChild(scriptEle);

let scriptEle1 = document.createElement("script");
scriptEle1.async = false;
scriptEle1.defer = true;
scriptEle1.setAttribute("src", "./t1.js");
document.head.appendChild(scriptEle1);
</script>
</head>
<body></body>
</html>

content of t.js:

console.log(1111);
let test = 1000;

content of t1.js:

console.log(2222);
console.log(test);

how to wait until a dynamically included javascript file is properly loaded?

you can promisfy the loading process, by creating a promise on first script and then on the second script check if the promise is resolved.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf8"/>
<script type="text/javascript">
var isLoaded = new Promise((res,rej) => {
function include_once(url) {
/*
[additional code to check if 'url' was already included]
*/
var script = document.createElement("script");
script.type = "text/javascript";
script.onload = () => res()
script.onerror = () => rej()
script.src = url;
document.head.appendChild(script);
}
include_once("https://code.jquery.com/jquery-3.6.0.min.js");
})

</script>
</head>
<body>
<script type="text/javascript">
isLoaded.then(() => {
$(document).ready(function(){
console.log("ready");
});
})
</script>
</body>
</html>


Related Topics



Leave a reply



Submit