Load external javascript after click a button - javascript

I want to load a javascript from an external source on my site, after clicking on a button.
I tried the following solution. Java script code, which is executed after clicking on the button:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "scrSource";
document.getElementsByTagName("head")[0].appendChild(script);
So now I can see the javaScript in my head, but it was not executed.
So when I load my external script with the normal way (when the page is loading) in the header, it loads a few other java script sources.
But with my solution (load file after clicking a button), I only put it in the head and no further action is happening.
Do someone have any ideas how I can solve this problem? (and I´m not allowed to use jQuery, only java script)

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);
}
loadScript("https://cdnjs.cloudflare.com/ajax/libs/Faker/3.1.0/faker.min.js", function(){
//initialization code
alert('loaded: ' + faker.name.findName());
});
A simple Google search of "Load external javascript" returns this link. The function you see it is from there. It's and old one but it works.
I use Faker.js to generate random data as confirmation that the library loaded is ready to be used.
It handles onreadystatechange/onload so you can define a callback to start using the library you've just downloaded.

Related

Javascript: best way to wait for script loaded synchonously before executing function?

I have the following problem:
I load a page inside a modal dialog. This page uses jQuery as dependency. Since I already use jQuery on the main page, for me, it is always available. Now we have the usecase, that also different pages (hosted on different domains) need to load that page if necessary.
So, I check if the jQuery variable exists on this page and if yes, just go on with my code.
If it does not exist, on top of the template, I dynamically create a script element like this:
<script>
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "path/to/jQuery";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
And at the end of the template, I use a IIFE (to scope the jquery variable)
(function ($) {
.... code ....
})(jQuery);
However, since with this method, the script gets loaded asynchronously, sometimes I get the error: jQuery is undefined.
Now I came up by loading it synchronously, like this:
var xhrObj = new XMLHttpRequest();
// open and send a synchronous request
xhrObj.open('GET', "jquery.min.js", false);
xhrObj.send('');
// add the returned content to a newly created script tag
var se = document.createElement('script');
se.type = "text/javascript";
se.text = xhrObj.responseText;
document.getElementById('placeholder').appendChild(se);
This works fine, but the warning "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. to the end user's experience." made me think.
However, now I changed my code and just said
if (!window.jQuery) {
document.write('<scr' + 'ipt src="jquery.js"' + '>' + '</scr' + 'ipt>');
}
on top of my Template.
Dear javascript gurus, is this a reliable solution?
Use the onload attribute in async javascript
<script async src="siteScript.js" onload="window.MyInitialisation()"></script>
In javascript it would look like this:
<script>
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.async = "async";
script.defer = "defer";
script.onload = function() {window.MyInitialisation()}
script.src = "path/to/jQuery";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>

phonegap - dynamically adding javascript

Developing phonegap application which loads google map. Using below two javascript for google map. One javascript is loaded from locally while other javascript loaded from server.
var script = document.createElement('script');
script.src = 'http://maps.google.com/maps/api/js?sensor=true';
script.type = 'text/javascript';
document.head.appendChild(script);
script.onload = function () {
var script1 = document.createElement('script');
script1.src = 'js/jquery.ui.map.js';
script1.type = 'text/javascript';
document.head.appendChild(script1);
script1.onload = function () {
alert(google.maps.LatLng);
}
};
Both javascripts should be loaded after html page is loaded. Tried below code and referred various blogs, but its not working.
If same scripts written in header tag of html page, then it working perfectly. but in my application i need it to be loaded dynamically.
Please help....
Solved:
var doc_write = document.write; // Remember original method;
document.write = function(s) {$(s).appendTo('body')};
$.getScript('http://maps.google.com/maps/api/js?sensor=true').done(function()
{
$.getScript('js/jquery.ui.map.js').done(function()
{
document.write = doc_write; // Restore method
setTimeout(function()
{
alert(google.maps.LatLng);
},1000);
})
.fail(function(jqxhr, settings, exception)
{
alert(exception); // this gets shown
document.write = doc_write; // Restore method
});
}).fail(function()
{
alert('failed to load google maps');
});
Problem:
It takes some time to initialise.
Call your javascript function after device get ready function. Because if you are using phone gap through Xcode, the device get ready function take some time to load and your script is called before it.
Don't do it in this way
Load it in footer section of your application

Method to see jQuery files are loaded completely then execute the function related to it

Method to see jQuery files are loaded completely then execute the function related to it
I want to show my div only when all the jQuery files related to that div is loaded.
document ready and window load function doesn't work.
How to write a conditional function where u can check whether all the jQuery is loaded then show the div.... i am calling all my jQuery files in an external js file, (basically i am trying to create a plugin for my client so that my external.js file will work from my server remotely).
my external.js file goes like this:
if (typeof jQuery === "undefined") {
var script = document.createElement('script');
script.src = 'js/jquery-1.7.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
}
if (typeof jQuery === "undefined") {
var script = document.createElement('script');
script.src = 'js/fancybox.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
}
document.ready = function() {
$(document).ready(function(){
$("#addimage").html("<a id='fancybox' href='large"+clientID+".jpg'><img border=0 src='thumb"+clientID+".jpg'/></a>");
}
});
so i want this addimage div work only my jquery files is loaded completely
use
if (jQuery) {
// jQuery is loaded
} else {
// jQuery is not loaded
}

JavaScript - function to load external JS files is needed

Recently I added to my website facebook like button, twitter follow us button and google +1 button. I want their JS scripts to load when I tell them to load.
Therefore, I need a function that load external JS files. I don't need to know when the file finished to load (callback is not needed).
I found some methods/functions on the Internet, but I want to know which would be the best choice for this situation?
4 ways to dynamically load external JavaScript
Dynamically loading JS libraries and detecting when they're loaded
The best way to load external JavaScript
Thanks.
Edit:
Added the methods/function I found.
I would recommend using jQuery's getScript(). For the twitter-button, you would load the corresponding script like that:
$.getScript("//platform.twitter.com/widgets.js")
Of course you would have to load jquery in your script first and do not forget to add the markup needed for the twitter-button in your html.
This might be helpful:
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);
}
Something like
function getScript(url) {
e = document.createElement('script');
e.src = url;
document.body.appendChild(e);
}
getScript('jstoload.js');
this?
The YUI Loader sounds like a good choice for you. It will also allow you to add your own custom modules, so you can load on demand, as well as load all other JS files that are required as well.

How to do a success callback when loading JS includes from another script file

I have legacy web app situation where I can't load jquery.min.js from a script tag in the HTML markup.. so I have to load it with some js in another existing script file
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
head.appendChild(script);
The problem is.. when the include load is slow.. there are jQuery functions
(also dynamically loaded on the page) that try to run and can't find jQuery
Is there some cross-browser way to do a callback in the above code that calls the jQuery ready function after the jquery.min.js include file finishes downloading from the CDN? Thanks,
EDIT:
Using Mike's code this is working with onload for nearly all browsers except
IE 8 or earlier.. and other browsers which need onreadystatechange I guess
JSFIDDLE HERE:
http://jsfiddle.net/BmyGC/
try
if(script.onreadystatechange)
script.onreadystatechange = function()
{
if(script.readyState == "complete" || script.readyState=="loaded")
{
script.onreadystatechange = false;
console.log("complete");
}
}
else
{
script.onload = function()
{
console.log("complete");
}
}
I would put my jquery-based code in yet another separate javascript file, and load that file in exactly the same way you are loading the jquery.min.js. Just do so immediately after jquery.min.js. That should work.
edit
Okay, since that isn't working, try this:
function jqChecker()
{
if (! jQuery )
{
setTimeout(jqChecker, 500); // adjust as needed.
}
else
{
// insert code to dynamically load your external js file here
}
}
jqChecker();

Categories