Dynamically Load a JavaScript File

Dynamically load JS inside JS

jQuery's $.getScript() is buggy sometimes, so I use my own implementation of it like:

jQuery.loadScript = function (url, callback) {
jQuery.ajax({
url: url,
dataType: 'script',
success: callback,
async: true
});
}

and use it like:

if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
//Stuff to do after someScript has loaded
});

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);
}
};

How do I load a javascript file dynamically?

You cannot embed HTML in Javascript in that way. Basically, what you want is to embed a script element, pointing to a certain javascript file when clicking a button. That can be done with combining events with DOM:

<script type="application/javascript">
function loadJS(file) {
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = file;
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}
</script>
<button onclick="loadJS('file1.js');">Load file1.js</button>
<button onclick="loadJS('file2.js');">Load file2.js</button>

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/

How to Dynamically Load Javascript File into HTML

So I found the issue was with the order that I was resolving code. It took forever to find because there was nothing inherently wrong with my code, but the sequence was wrong.

I was calling everything in the correct order, but the order that things were resolving in my network panel were incorrect.

Once I fixed the sequence that things were being loaded into the DOM, everything worked as expected.

Fix #1

Because my XMLHttpReqests should be asynchronous, I put all the calls into a single Javascript file so they would run synchronously.

I needed Javascript files to be loaded in the tag before loading function calls that reference those files.

The function calls I wrapped in window.onload = function(){}.

Basically my final solution was for any <script>code</script> that I was dynamically placing in example.html I would wrap in window.onload = function(){}.

i.e. <script>window.onload = function(){ code }</script>

Fix #2

I was using the onload wrapper window.onload = function(){} in a location that did not make sense. Also it may have been nested within another window.onload function at one point while debugging, which probably didn't help.

How to load external scripts dynamically in Angular?

If you're using system.js, you can use System.import() at runtime:

export class MyAppComponent {
constructor(){
System.import('path/to/your/module').then(refToLoadedModule => {
refToLoadedModule.someFunction();
}
);
}

If you're using webpack, you can take full advantage of its robust code splitting support with require.ensure :

export class MyAppComponent {
constructor() {
require.ensure(['path/to/your/module'], require => {
let yourModule = require('path/to/your/module');
yourModule.someFunction();
});
}
}

Dynamically load several JS files and fire a callback when all are ready

I would suggest you to make an array of your resources rather than an object if you care about the order of their loading. I hope this solution will solve your issue.

var urls = ['https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js',
'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.slim.js'
];

var i = 0;

var recursiveCallback = function() {
if (++i < urls.length) {
loadScript(urls[i], recursiveCallback)
} else {
alert('Loading Success !');
}
}

loadScript(urls[0], recursiveCallback);

function loadScript(url, callback) {

var script = document.createElement("script")
script.type = "text/javascript";

if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState == "loaded" ||
script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function() {
callback();
};
}

script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}

Working Fiddle : https://jsfiddle.net/nikdtu/6uj0t0hp/

Dynamically load Javascript file one at a time

Use the script async attribute

Seems like the problem could be solved easily by setting the async attribute to false. This way the scripts load in order and Firebase works. If set to true then the scripts can load in unpredictable order based on size, location, etc. And Firebase may fail because firebase-app.js must always be loaded first. And in fact, you'll see those errors if you set async = true in the snippet.

  script.async = false;

Run the snippet to see the scripts load in order:

  [

"https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js",
"https://www.gstatic.com/firebasejs/8.10.1/firebase-analytics.js",
"https://www.gstatic.com/firebasejs/8.10.1/firebase-app-check.js",
"https://www.gstatic.com/firebasejs/8.10.1/firebase-auth.js",
"https://www.gstatic.com/firebasejs/8.10.1/firebase-firestore.js",
"https://www.gstatic.com/firebasejs/8.10.1/firebase-functions.js",
"https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js",
"https://www.gstatic.com/firebasejs/8.10.1/firebase-storage.js",
"https://www.gstatic.com/firebasejs/8.10.1/firebase-performance.js",
"https://www.gstatic.com/firebasejs/8.10.1/firebase-database.js",
"https://www.gstatic.com/firebasejs/8.10.1/firebase-remote-config.js",
"https://code.jquery.com/jquery-3.6.0.min.js",
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"

].forEach(src => {

let script = document.createElement('script');
script.src = src;

// if set true the scripts load in any order and Firebase may fail
script.async = false;

script.onload = console.log(src);

document.body.append(script);

});
Loading scripts...


Related Topics



Leave a reply



Submit