Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import the external JS with callback function?

I am using Google API, based on their link I have to put the following script in the HTML file

<script src="https://apis.google.com/js/client.js?onload=callback"></script>

The custom callback function is being loaded after the client.js is loaded successfully.

function callback() {
  var ROOT = 'https://your_app_id.appspot.com/_ah/api';
  gapi.client.load('your_api_name', 'v1', function() {
    doSomethingAfterLoading();
  }, ROOT);
}

I would like to

  1. Separate HTML with JS file
  2. I downloaded the client.js file and put it in my local repo. But for reducing web request I would like to concat the client.js with other JS file. But I have no idea how to load the content with the concatenated JS file with the callback is being called

Thanks in advance

like image 439
Winston Avatar asked Dec 24 '22 08:12

Winston


1 Answers

If you are looking for javascript only solution:

var sScriptSrc = "https://apis.google.com/js/client.js?onload=callback"
loadScript(sScriptSrc);

function loadScript(sScriptSrc) {
    var oHead = document.getElementsByTagName("HEAD")[0];
    var oScript = document.createElement('script');
    oScript.type = 'text/javascript';
    oScript.src = sScriptSrc;
    oHead.appendChild(oScript);
    oScript.onload = loadedCallback();
}

function loadedCallback() {
    alert("WoHooo I am loaded");
}

See it running here: JSFiddle

EDIT

Let me do some refining, if I understand correctly what you want to achieve:

I made a simple main html page:

<html>
<head>
<script src="client.js"></script>
</head>
<body>
    PAGE BODY
</body>
</html>

Which is loading client.js

client.js contains:

// you can call this function with
//     param1: src of the script to load
//     param2: function name to be executed once the load is finished 
function loadScript(sScriptSrc, loadedCallback) {
    var oHead = document.getElementsByTagName("HEAD")[0];
    var oScript = document.createElement('script');
    oScript.type = 'text/javascript';
    oScript.src = sScriptSrc;
    oHead.appendChild(oScript);
    oScript.onload = loadedCallback;
}

// let's load the Google API js and run function GoggleApiLoaded once it is done.
loadScript("https://apis.google.com/js/client.js", GoggleApiLoaded);

function GoggleApiLoaded() {
    alert("WoHooo Google API js loaded");
}

Of course, instead of GoggleApiLoaded example function you could run a method which start the loading of different js and the callback of that one could load a next one and so on...

Is this what you were looking for?

like image 123
DDan Avatar answered Jan 04 '23 23:01

DDan