How to Load a JavaScript File Dynamically

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

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>

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

Is it possibly to re-load a JS script file dynamically?

Even though your explanation is extremely messy, I’ll try to stick to the title and provide an example of how you might re-load a specific JS file dynamically (apologies if it is not what you were looking for, but then you’d better re-write your question).

I guess you did not search Google a lot, because in this SO answer you find how to re-load a JS file:

function reloadJs(src) {
src = $('script[src$="' + src + '"]').attr("src");
$('script[src$="' + src + '"]').remove();
$('<script/>').attr('src', src).appendTo('body');
}

As the user points out, you can remove the old tag, but for that the code runtime should already be done. You just need to call the function specifying the source’s address.

That will literally reload the file, but you want to pass some modifications, therefore you need to run on server-side a script that serves the files according to your needs. You can specify information as GET parameters in your JS reload, such as ‘?parameter1=data1¶meter2=data2’.

However, I do not recommend to do that, form me the JS code should instead make AJAX calls to modify its behaviour, and not reload the entire file. But that is up to you.

Edit

If I understand you correctly, what you want to do actually is to give the client the actual JS code, and not to run the file in the server, according to some diagrams they design which will eventually build into JS code. Then what you could to is to have a <div> tag with a <pre><code> tags inside whose content is changed with jQuery through an AJAX call.

Then you should not actually load the JS file as a script, since that will make the browser execute it. What you have to do is something like this:

index.html

<div>
<pre>
<code id=“myCode”>
Your JS file will show soon.
</code>
</pre>
</div>

As from jQuery documentation:

script.js

var jqxhr = $.get( "myFile.js", function(data) {
$(“#myCode”).html(data)
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});

You obviously have to reference the JS file in your HTML file or it won’t load. You can encapsulate that inside a function and call it according to your convenience.



Related Topics



Leave a reply



Submit