Get alert when external JavaScript is done - javascript

I am loading a script from the google plus button only when the user requests it. The code that is used is the following:
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
When I fire this script it will change the placeholder into the google plus button. The placeholder looks like this:
<g:plusone size="tall" annotation="none"></g:plusone>
There are a few other buttons I load like this, only when needed.
Now sometimes the buttons take a while to load. Is there a way get an alert when all the buttons are loaded.
I can then just display a loader until it is fully loaded, and then display it nicely.
I use jQuery as my javascript framework.
Edit
For a better solution check out this question: Invoking handler when all scripts finished loading via $.getScript
A better way to go is using jQueries deffered object. I added a small example and fiddle to the answer.

jQuery provides a mechanism to define a script load handler:
$.getScript( 'https://apis.google.com/js/plusone.js', function () {
// the script has loaded and executed
});
This handler is invoked after the script has executed, so it should suit your needs...

If you want to add the feature without modifying existing content, use the code below:
(function(){
var poller = window.setInterval(function(){//Set poller
if($('g\\:plusone').length == 0){ // When the document doesn't have
clearInterval(poller); // any g:plusone elements, clear
// poller, and execute your code
//Run your code..
}
}, 200); //Checks at a frequence of 200ms
})();

Related

jQuery cannot be accessed properly after being loaded dynamically?

I am trying to write a small check that will test for jQuery, and if not present, dynamically load a copy so that a script can be run by it. It sets to no conflict in case anything else is present that also uses $, and then runs the script - a small menu.
However, upon actually testing this jQuery is loaded from the script, but fails to execute: "jQuery is not defined."
I know that jQuery has to come first before any functions that use it, but is there any way to fix this when it is dynamically installed?
(function() {
console.log("Loaded");
if(!window.jQuery) {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
jQuery.noConflict();
}
})();
You're not waiting until the script has loaded.
script.onload = function(){
// do whatever
};

Asynchronous script load issue

I'm trying to load a script from an external source after the user executes a click function. Like so:
$("#test-button").click(function() {
$.getScript("http://someurl.com/widget/javascript?key=4&t=uid&q=94777&show=all", function (data) {
$('#myDiv').append(data);
});
});
The script I'm loading (which I have no control over) includes a document.write, so I'm getting this error when I execute the click:
It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
I'm not sure how to get around this. I thought getScript would manage this.
It seems like you have append the script like text
please see this example
var script = document.createElement('script');
script.src = '../web3.0/lib/charts/google-charts.js';
document.body.appendChild(script);

loading a backup copy of jQuery when CDN is down

I have this code in a script we use for initializing all of our applications, it loads the jQuery from the google CDN amongst several other things that all of our applications require. Then when we load the specific program functionality we check to make sure that jquery has loaded, in case the CDN is down. The problem I am running into is it is still loading the second one. If I add a simple alert("Test"); after the line headTag.appendChild(jqTag); it works perfectly, but if I remove the alert it uses the second one. What gives?
They are loaded like so:
<script type="text/javascript" src="i-initializer.js"></script>
<script type="text/javascript" src="i-program.js"></script>
initializer script:
if(typeof jQuery=='undefined'){
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js';
headTag.appendChild(jqTag);
}
Then in another script we have the following:
if(typeof jQuery=='undefined'){
var header = document.getElementsByTagName("head")[0];
var qtag = document.createElement('script');
qtag.type = 'text/javascript';
qtag.src = 'http://feedback.oursite.com/scripts/jquery-1.8.3.min.js';
qtag.onload = checkjQueryUI;
header.appendChild(qtag);
}
else
{
jQCode();
}
jQCode() {
...
}
This is the technique used by HTML5 Boilerplate. First it loads the Google CDN script, then immediately checks if the global jQuery object exists -- if it doesn't, the CDN failed and a local copy is loaded instead.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.3.min.js"><\/script>')</script>
Your fallback code loads jQuery asynchronously.
That means that the rest of your scripts run before jQuery loads.
Adding an alert() call forces the rest of your code to wait (until you click OK); by the time that happens, jQuery will have loaded.
Instead, you can emit a new <script> tag using document.write() to load it synchronously.
Alternatively, you could wrap the rest of your code in a callback and call the callback(s) after jQuery loads.
If you do it this way, you should use a script loader library, which will handle all of that for you.

Detect whether external script has loaded

Using JavaScript, is there a way to detect whether or not an external script (from a third-party vendor) has completely loaded?
The script in question is used to pull in and embed the markup for a list of jobs and, unfortunately, doesn't make use of any variables or functions. It uses document.write to output all of the content that gets embedded in my page.
Ideally, I'd like to display some kind of loading message while I'm waiting for the external script to load, and if it fails to load, display a "We're sorry, check back later..." message.
I'm using jQuery on the site, but this external script is called before I make the jQuery call.
Here's what the document.write stuff from the external script looks like:
document.write('<div class="jt_job_list">');
document.write("
<div class=\"jt_job jt_row2\">
<div class=\"jt_job_position\">
Position Title
</div>
<div class=\"jt_job_location\">City, State</div>
<div class=\"jt_job_company\">Job Company Name</div>
</div>
");
Attach an function to the load event:
<script type="text/javascript" src="whatever.js" onload ="SomeFunction()" />
As far as your loading... problem goes, try displaying a div for loading and then just display:none-ing it in your onload function. Make sure to handle cases where your script fails to load too, though.
Script tags block downloads, so as long as the content dependent on your script is below where your script it loaded, you should be fine. This is true even if the script is in-line in the body of your page.
This website has a great example of how this works.
This obviously does not work if you're loading the scripts asynchronously.
Scripts without async or defer attributes are fetched and executed immediately, before the browser continues to parse the page.
Source: MDN
You could put a script block after it on the page:
<script src="external_script.js"></script>
<script type="text/javascript">
ExternalScriptHasLoaded();
</script>
Thanks for the assistance above, especially ngmiceli for the Steve Souders link!
I decided to take what's probably a "lazy" approach, and also forego the "loading" message:
$(document).ready(function(){
if ($('.jt_job_list').length === 0){
$('#job-board').html("<p>We're sorry, but the Job Board isn't currently available. Please try again in a few minutes.</p>");
};
});
Pretty simple, but I'm looking to see if an element with the .jt_job_list class is in the dom. If it isn't, I display an error message.
This worked for me: it does however, rely on the newer querySelector interface which most modern browsers support. But if you're using really old browsers, you can use getElement... and run a for loop.
function loadJS(file, callback, error, type) {
var _file = file ;
var loaded = document.querySelector('script[src="'+file+'"]') ;
if (loaded) {
loaded.onload = callback ;
loaded.onreadystatechange = callback;
return
}
var script = document.createElement("script");
script.type = (typeof type ==="string" ? type : "application/javascript") ;
script.src = file;
script.async = false ;
script.defer = false ;
script.onload = callback ;
if (error) {
script.onerror = error ;
}
else {
script.onerror = function(e) {
console.error("Script File '" + _file + "' not found :-(");
};
}
script.onreadystatechange = callback;
document.body.appendChild(script);
}
You could give what ever your looking for an ID
and check whether not the ID has been loaded using document.getElementById("ID");
Is that what your looking for not sure I fully understand?

Dynamically loading Java Script files

I would like to know if there is a way to dynamically load some JS files before "$(document).ready" gets called. These JS files should be loaded and available in the ready event handler.
Does jquery provide a way to do this?
The issue here (as you might expect) is the ability to load a specific localized version of my JS files depending on whichever locale/language is selected.
Thanks
If you want in pure javascript you can try this.
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.onreadystatechange= function () {
if (this.readyState == 'complete'){
//Your can write your code here
};
}
script.src= 'script.js';
head.appendChild(script);
Alertnatively you can use jQuery's getScript method
$.getScript("script.js", function(){
//Your can write your code here
});
Try this:
jQuery.getScript("url here")
http://api.jquery.com/jQuery.getScript/

Categories

Resources