Can I use jquery getScript() without a callback?

后端 未结 4 1883
忘掉有多难
忘掉有多难 2020-12-29 10:09

I need to use a javascript function from an external js file inside another js file. This is basically the code I\'ve tried:

$.getScript(\'js/myHelperFile.js         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 10:56

    Using the getScript() function on its own, I don't think you can. The problem is that the script is being loaded using AJAX (indeed, getScript is just a shorthand for a special $.ajax() function), and when the browser tries to execute the function on the next line, perhaps the server has not yet returned the file.

    If you do not wish to use a callback function, you will need to use the jQuery $.ajax() function in its original form (and forget about the getScript()), and set the transfer as synchronous. This way, you can be sure that the script will be loaded before execution of your code continues:

    $.ajax({
        url: url,
        dataType: "script",
        async: false
    });
    

提交回复
热议问题