简体   繁体   中英

call a function onload of external script

I'm playing around with Google Drive API, and noticed that they are calling a handleClientLoad function onload of the client.js.

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

Trying to avoid creating globals, I thought I would start with creating another js file, that would contain a module pattern and return handleClientLoad .

var module = (function (window, $) {

    'use strict';

     var module = {
         handleClientLoad: function () {
             console.log('ok, can access');
         }
     };

     return module;

}(window, jQuery));

And then I assumed I could just call the handleClientLoad by doing module.handleClientLoad , but that doesn't seem to be working.

    <script src="scripts/main.js"></script>
    <script src="https://apis.google.com/js/client.js?onload=module.handleClientLoad"></script>

Questions:

  1. Is it possible to call the module.handleClientLoad from onload of client.js?

  2. Appending onload and calling a function from a script file seems sloppy and obtrusive, no? Is there a cleaner way to know when the client.js has loaded?

  1. Have you tried debugger, and are you sure module. hanfleClientLoad exists at the time the callback is fired?

  2. You can poll for the existence of gapi.client as a global object. Give it a few milliseconds to initialise before invoking its methods.

I found that jQuery.getScript() worked quite nicely for this. Documentation here .

Instead including the <script> tag in the html page, I simply included the following line in my js file:

jQuery.getScript( "https://apis.google.com/js/api.js", handleClientLoad );

It might require slight tweaking for the way you structured your module, but I think this will be easier than passing a parameter to your <script> tag (at least I found it easier).

I know this is old, but I was messing around with this because this was related to a question on a test I was studying for. You can use onload like this when you call the script:

<script src="https://apis.google.com/js/client.js" onload="handleClientLoad()"></script>

For anyone wanting to know why this won't work:

<script src="https://apis.google.com/js/client.js">handleClientLoad()</script>

It's because any code between a script tag with "src=" in it will be ignored.

And I'm not sure why using onload= in the script tag calling the external script is any more obtuse than appending?onload=module.handleClientLoad to the source? But that's just me.

In the end, I'm not sure why exactly this was a question on the test, because based on searching, this doesn't seem to be a common thing that anyone does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM