Here's my dilemma: A browser hard refresh empties the browser cache, and when that happens while internet connection is lost, I cannot use my app when the internet connection resumes. I therefore want to manually (seamlessly) reload Google's client.js script and related Youtube APIv3 via a button.
Is there a proper way to defer a function (fetching Youtube data) until all required Youtube scripts are successfully manually loaded? That function would firstly have to check if the needed Youtube resources are available in the browser cache before polling the needed external resources.
I have this code but do not know how to set up connection()
and defer
correctly. Help would be appreciated:
function connection() {
// How to verify if needed resources are in browser cache, if not,
// fetch them externally?
// apis.google.com/js/client.js?onload=googleApiClientReady
}
function googleApiClientReady(){ gapi.client.setApiKey('API key');
gapi.client.load('youtube', 'v3', function(){
appdefaults();
});
}
function lostconnection() {
alert('Connection lost.');
}
function verifynetwork(){ // Check connection status
var i = new Image();
i.onload = connection;
i.onerror = lostconnection;
i.src = '//img.youtube.com/vi/4xmckWVPRaI/1.jpg?d=' + escape(Date());
// escape(Date()) is necessary to override possibility of image
// coming from cache.
}
$(function(){
$('#YTdata').on('click', function(){
verifynetwork();
ytdata(); // Defer this function until verifynetwork() has completed?
}
<button id="YTdata">Get data</button>