How to run functions from a dynamically loaded script - javascript

I am trying to load a js script dynamically in index.html file using appendChild DOM method. And I am trying to use some functions from that dynamically loaded js in next line itself but I am getting error that the specified function is undefined. I understand that this error is because of async behavior of loading scripts in browser. I also used async flag as false but no use. Below are sample code.
<script>
var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.async = false;
js.src = "https://example.com/test.js"; // There are two variants of test.js is there. Will be changing it dynamically based on conditional check.
head.appendChild(js);
</script>
<script>
test(); // Method inside test.js
</script>
I want test.js to be loaded immediately after executing appendChild code part. Please help me on this. Please suggest if there is any other way for my purpose.

Synchronized XHRs are deprecated. You need to add an event listener so you can call your code as soon as the script is loaded. Example below:
var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
head.appendChild(js);
js.onload = function() {
console.log("yes", window.$)
};
js.src = "//code.jquery.com/jquery-3.3.1.min.js";
console.log("nope", window.$)

Related

remove js code from page

I added js code dynamically:
var head = document.getElementsByTagName("head")[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.id ="jsChange";
js.src = "myRoute.js";
head.appendChild(js);
It works fine, the problem is when I try to remove, I can get the way.
$('#jsChange').remove() //Doesnt work
I also try to add a div in head and put the js inside:
$('#divToJS').append(js);
and:
$('#divToJS').empty(); // doesnt work
How can I do it?
Your empty and remove both need () on the call.
E.G.
$('#jsChange').remove to $('#jsChange').remove();
$('#divToJS').empty to $('#divToJS').empty();
Unless i've misread the question, this should solve your issue.

Conditionally load JavaScript file

I need a JS statement that determine which JavaScript file to use.
I have one file:
<script type="text/javascript" src="js/jquery_computer.js"></script>
But when the screen width is less than 500px, I want load another file instead:
<script type="text/javascript" src="js/mobile_version.js"></script>
I have tried everything and it is not working.
You'd have to create that markup yourself in JS. Something like this:
var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
js.type = "text/javascript";
if (screen.width > 500)
{
js.src = "js/jquery_computer.js";
}
else
{
js.src = "js/mobile_version.js";
}
head.appendChild(js);
If you want the script loaded asynchronously, the other answers here do that.
If you want it loaded synchronously with page load, this is one of the very, very few remaining valid uses cases for document.write:
<script>
(function() { // Scoping function to avoid globals
var src = /*you want the main version*/ ? "jquery_computer.js" : "mobile_version.js";
document.write('<script src="js/' + src + '"><\/script>');
})();
</script>
(I've removed type because JavaScript is the default, specifying it isn't useful.)
Maybe you can use matchMedia.js and can load a script using jQuery.getScript
$(function(){
if (matchMedia('only screen and (max-width: 500px)').matches) {
$.getScript(...);
}
});
Best would be to use built-in matchMedia API.
var script = document.createElement('script');
script.type='text/javascript';
if(window.matchMedia("(min-width:500px)").matches) {
script.src = 'js/jquery.slitslider.js';
}else{
script.src = 'js/mobile_version.js';
}
document.getElementsByTagName('head')[0].appendChild(script);
Drawback is that it is not supported in IE < 10
You don't need jQuery for this, it suffices to create the <script> tag in the DOM dynamically:
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
if (<screen-width less than 500>)
script.src = "js/mobile_version.js";
else
script.src = "js/jquery_computer.js";
head.appendChild(script);
$(function(){
var width = $(document).width(),
mobile = 500;
if (width > mobile) {
$('head').append('<script class="desktop" type="text/javascript" src="js/jquery_computer.js"></script>');
$('head').find('.mobile').remove();
}
else
{
$('head').append('<script class="mobile" type="text/javascript" src="js/mobile_version.js"></script>');
$('head').find('.desktop').remove();
}
});
just use if else to detect condition and use class on script element
may be it help
You could use the async import() if you like.
import(condition ? 'js/desktop_version.js' : 'js/mobile_version.js')
In a script tag with <script type="module"> or inside a module loaded with import() from a regular <script> you can also use top-level await in the newest (experimental) browsers
<script type="module">
await import(condition ? 'js/desktop_version.js' : 'js/mobile_version.js')
</script>
But it won't work for every script.
A common reason why is those UMD module bundler that adds a closure (function(global){...}(this)) since this is undefined in modules.
Third party scripts needs to have CORS enable to load
Won't work in IE, but it's dead anyway
See other known differences
you can use $.getScript in jQuery
see here for details

Is it possible to execute Javascript code that was retrieved using pjax?

Let's say I have some simple Javascript like:
<script>
var hello = function(){
alert("Hello World!");
}
</script>
.. on a page helloworld.html. If I loaded this script block into another page using Pjax. How do I execute the function hello()?
For security reasons, many browsers will not run Javascript injected by innerHTML, which I'm thinking Pjax likely uses. (Here's a minimal example.)
Maybe the solution proposed in Pjax's issue #48 will help
What worked for me was to place my jQuery code in a function, call it
normally on document.ready (for non-pushState browsers), and then bind
the function to pjax:end, i.e.:
$('body').bind 'pjax:end', mainFunction
This is possible with PJAX. You just need to have the script tag with type text/javascript.
Code from PJAX library:
function executeScriptTags(scripts) {
if (!scripts) return
var existingScripts = $('script[src]')
scripts.each(function() {
var src = this.src
var matchedScripts = existingScripts.filter(function() {
return this.src === src
})
if (matchedScripts.length) {
matchedScripts.remove();
}
console.error("FOUND SCRIPTS", scripts, matchedScripts.length);
var script = document.createElement('script')
script.type = $(this).attr('type')
script.src = $(this).attr('src')
document.head.appendChild(script)
})
}

Setting contents of script with jQuery

Is it possible to set the contents of a script element with jQuery? Currently I have:
$(document).ready(function () {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://somedomain.com/somescri...";
$("head").append(s);
});
What if I wanted to replace src property with actual javascript code? Is this possible with jQuery or Javascript?
There's a better way to write that, using $.getScript:
$.getScript("http://somedomain.com/somescri...")
As mentioned, you're looking for eval
eval('x = 2');
alert(x)

Can't access variables from dynamically loaded javascript

I'm using a fairly simple system to load javascript dynamically:
include = function (url) {
var e = document.createElement("script");
e.src = url;
e.type="text/javascript";
document.getElementsByTagName("head")[0].appendChild(e);
};
Let's say I have a file test.js which has the following contents:
var foo = 4;
Now, in my original script, I want to use
include(test.js);
console.log(foo);
However, I get a 'foo has not been defined' error on this. I'm guessing it has to do with the dynamic script being included as the last child of the <head> tag. How can I get this to work?
It is because you have to wait for the script to load. It is not synchronous like you would think. This may work for you:
include = function (url, fn) {
var e = document.createElement("script");
e.onload = fn;
e.src = url;
e.async=true;
document.getElementsByTagName("head")[0].appendChild(e);
};
include("test.js",function(){
console.log(foo);
});
That is one problem, but it also takes time for the browser to download and parse the remote JS file — and it hasn't done that before you call console.log.
You need to delay things until the script has loaded.
This is easiest done by letting a library do the heavy lifting, jQuery has a getScript method that lets you pass a callback to run when the script has loaded.

Categories