Is the callback on jQuery's getScript() unreliable or am I doing something wrong?

后端 未结 11 1242
Happy的楠姐
Happy的楠姐 2020-12-03 03:17

I\'m using the following bit of script to load another one:

$.getScript(\"CAGScript.js\", function () {
    try {
        CAGinit();
    } catch(err) {
              


        
相关标签:
11条回答
  • 2020-12-03 03:39

    Seems like jQuery handles cross-domain and same domain requests just fine now. For cross domain requests, it will add a script tag and subscribe to error and load events and appropriately call your done and error callbacks, it's an error only if a request fails, errors evaluating the script will still be considered a success as far as the request is concerned. For same-origin, it will do an XHR request and then do a globalEval and once it's done, call your done callback, if anything fails in the process, it will call your error callback.

    Using XHR has a few issues, it breaks the debugger, sourcemaps and it relies on a globalEval, which has issues with ContentSecurityPolicy. For that an consistency, we simply add a script tag when we load scripts.

    var scriptElement = $("<script>").prop({src: url, async: true}); scriptElement.one('load', ()=> ...); scriptElement.one('error', (evt)=> ...); document.head.appendChild(scriptElement[0]);

    If you want to do it without jQuery search for Dynamically importing scripts in this article

    Hope this helps.

    0 讨论(0)
  • 2020-12-03 03:42

    In order to make sure CAGScript.js is LOADED and EXECUTED before calling CAGinit function, the surest way is to have the function call inside CAGScript.js.

    CAGScript.js:

    
    
        ...
        /*
        your code
        */
        function CAGinit(){
        ...
        }
        ...
        /* last line */
        CAGinit();
    
    

    and then, in your main file just call getScript():

     
    
        $.getScript("CAGScript.js");
    
    
    0 讨论(0)
  • 2020-12-03 03:48

    If the file is held on the same domain then jQuery will use XHR to retrieve its contents and then will globally "eval" it. This should work fine but if you're having problems then I'd suggest using the alternative method of injecting a script tag. Unfortunately, jQuery doesn't expose this functionality so you'll have to do it yourself:

    var script = jQuery('<script/>').attr('src', 'CAGSCript.js').appendTo('head');
    
    var timer = setInterval( function(){ 
        if (window.CAGInit !== undefined) {
            clearInterval(timer);
            script.remove();
            // Do your stuff:
            CAGInit();
        }
    }, 200);
    

    It'd be best to abstract this to a function; the above is just an example...

    0 讨论(0)
  • 2020-12-03 03:48

    I wanted to have something similar to auto_load in PHP implemented in JS, the typical solution is using try-catch on all functions.. when the function is missing we jump to downloading its library.. My solution is taken from Pieter solution as follows:

    function CheckUserPW(username,password){
        try{
           loginCheckUserPW(username,password);
        } catch(err) {
            $.getScript('login.js', function(xhr){ 
                eval(xhr);
                loginCheckUserPW(username,password);
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-03 03:50

    I noticed the same issue with FF 3.6.

    A solution is to load the script synchronously.

    As mentioned in jQuery's documentation, getScript is shorthand for:

    $.ajax({
      url: url,
      dataType: 'script',
      success: success
    });
    

    Everything works fine if I use the following instead of getScript:

    $.ajax({
      url: url,
      dataType: 'script',
      success: success,
      async: false
    });
    
    0 讨论(0)
  • 2020-12-03 03:51

    Yeah, I've discovered too that getScript is unreliable in FireFox, firing the callback before the script has been downloaded and/or executed. (Using JQuery 1.41 & FireFox 3.6. Issue doesn't seem to afflict IE, Chrome or Opera.)

    I haven't done extensive testing, but it seems to only happen with some specific scripts...not sure why.

    RaYell's suggestion doesn't work, as getScript will report success even though the script has not yet been eval'ed. Pieter's suggestion in most cases causes the code to be eval'ed twice, which is inefficient and can cause errors.

    This alternative seems to work where getScript does not. Note that it seems to be adding a SCRIPT DOM element, whereas getScript does XHR.

    http://www.diveintojavascript.com/projects/sidjs-load-javascript-and-stylesheets-on-demand

    0 讨论(0)
提交回复
热议问题