1

As title says I need lazy javascript loading until when necessary. I know people have asked about this many times on SO and there are a few ways to do so:

  1. create a script element and append it to head
  2. use jquery's getScript function. this is what I actually used:

    $.getScript( some_url )
    .done(function( script, textStatus ) {
      console.log( textStatus );
    })
    .fail(function( jqxhr, settings, exception ) {
      $( "div.log" ).text( "Triggered ajaxError handler." );
    });
    

The problem with both approaches is, if the script at *some_url* needs to further load other files, even though some_url finishes loading and executing to me it's still in premature state and fails all my following code. One example is when I try to load Google Maps API at https://maps.googleapis.com/maps/api/js?key=abc&sensor=true at its bottom we can see:

getScript("https://maps.gstatic.com/intl/en_us/mapfiles/api-3/16/3/main.js");

So when my getScript finishes Google's getScript might still be loading. Any thought to solve this problem?

Yandong Liu
  • 335
  • 4
  • 13
  • 2
    You can't! There's no sure way to know what other scripts a script includes, all you can do is wait for the original script. If you know what's supposed to load, such as gstatic, you can check for certain properties etc. in an interval until they are available. – adeneo Mar 11 '14 at 22:10
  • 1
    possible duplicate of [Async Google Maps API v3 undefined is not a function](http://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function) – Dr.Molle Mar 11 '14 at 22:35
  • @Dr.Molle yes for this particular problem the answer provided in your link would work and I verified it. Thanks for that but I'm also wondering if there's a solution to this issue in general even if API provider doesnt offer a callback function. – Yandong Liu Mar 12 '14 at 19:54
  • well there was an answer suggesting (also by @adeneo) to query the validity of the object I need in order for following code to execute. Not so sure why that answer was removed but I thought it wasnt a bad idea. My following code failed because that API object is null. After some milliseconds when that object is loaded I'm able to proceed. – Yandong Liu Mar 12 '14 at 19:56
  • @Yandong Liu: there is no general solution, when the API-provider didn't provide any option to detect the completion of the ressource-loading/readiness you'll need a custom implementation – Dr.Molle Mar 12 '14 at 23:37

0 Answers0