Jquery to Load JavaScript File Dynamically

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
if(typeof TinyMCE == "undefined") {
$.getScript('tinymce.js', function() {
TinyMCE.init();
});
}
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

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

Load JavaScript dynamically

You may want to use jQuery.getScript which will help you load the Google Maps API javascript file when needed.

Example:

$.getScript('http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=true', function(data, textStatus){
console.log(textStatus, data);
// do whatever you want
});

Dynamically load javascript files

Try appending the child in the loop. In your example, you only have one instance of script.

for(var i = 0; i<_scriptUrl.length; i++)
{
var jsElm = document.createElement("script");
jsElm.type = "application/javascript";
jsElm.src = _scriptUrl[i];
document.body.appendChild(jsElm);
}

If you're serious about async loading of js, try requirejs.

Dynamically load javascript files and make sure they are cached

You can easily check if they are cached by loading your page for a second time with the network tab of the developer tools of your browser opened. You can tell by the way the scripts are loaded whether the file is cached or not.

They should be, by the way. You're basically inserting a script tag through JavaScript, after which the script is loaded as it would be if the tag was already in the page.

If you make it load asynchronously, you can attach an onload event to a script tag, which will fire as soon as the script is loaded. This should work in any modern browser, including IE9+ in standard mode. If you need support for IE8, you will have to do some extra work, which is what $.getScript() also does. An in-depth discussion of that jQuery functionality, with alternative code snippets can be found in the question 'onload' handler for script tag in Internet Explorer.

is there a way to dynamically load js file as es6 module? (like $.getScript)

if you want to load JS files dynamically it is possible to use dynamic imports:

import('yourFile').then(() => ...)

Some info on it on Webpack page https://webpack.js.org/guides/code-splitting/ and there https://v8.dev/features/dynamic-import



Related Topics



Leave a reply



Submit