JavaScript:JavaScript 什么时候评估一个函数,onload 或什么时候调用函数?

标签 javascript jquery google-maps asynchronous

JavaScript 什么时候计算一个函数?是在页面加载时还是在调用函数时?

之所以这么问,是因为我有如下代码:

function scriptLoaded() {
   // one of our scripts finished loading, detect which scripts are available:
   var jQuery = window.jQuery;
   var maps = window.google && google.maps;

   if (maps && !requiresGmaps.called) {
     requiresGmaps.called = true;
     requiresGmaps();
   }
   if (jQuery && !requiresJQuery.called) {
     requiresJQuery.called = true;
     requiresJQuery();
   }
   if (maps && jQuery && !requiresBothJQueryGmaps.called) {
     requiresBothJQueryGmaps.called = true;
     requiresBothJQueryGmaps();
   }
}
// asynch download of script
function addScript(url) {
    var script = document.createElement('script');
    script.src = url;
    // older IE...
    script.onreadystatechange=function () {
      if (this.readyState == 'complete') scriptLoaded.call(this);
    }
    script.onload=scriptLoaded;

    document.getElementsByTagName('head')[0].appendChild(script);
}

addScript('http://google.com/gmaps.js');
addScript('http://jquery.com/jquery.js');

// define some function dependecies
function requiresJQuery() { // create JQuery objects }
function requiresGmaps() { // create Google Maps object, etc }
function requiresBothJQueryGmaps() { ... }

我想做的是执行我的 JavaScript 的异步下载,并尽早开始执行这些脚本,但我的代码依赖于脚本明显下载和加载的时间。

当我尝试上面的代码时,我的浏览器似乎仍在尝试计算我的 require* 函数中的代码,甚至在这些函数被调用之前。它是否正确?还是我误解了我的代码有什么问题?

最佳答案

函数在调用时被评估。

例如

function test() {
    window.foo = 'bar';
}

console.log(window.foo); // => undefined
test();
console.log(window.foo); // => bar

尽管test在第一个 console.log 之前创建, window.foo直到 test 才被填充实际上被调用了。

如果您的 requires*函数挂起/阻塞,那么您需要显示这些代码(为什么不提供有问题的代码的源代码?)

编辑:

目前,当您附加已​​加载的 <script> 时,您的网站对我来说是空白的到 <head> .

无论如何,一个快速的解决方法是将您想要的脚本放在页面底部附近,</body> 之前。 , 因为只有 <head> 中的脚本将在加载时完全阻塞页面。

有一些优雅的方法可以延迟加载资源,但是,为了保持简单..

<script type="text/javascript" src="http://path/to/jquery.js"></script>
<script type="text/javascript">
requiresJQuery(); // jQuery is available at this point
</script>
</body>

重点是,自<script>放置在您的主要元素之后,DOM 元素将在浏览器开始下载您的其他库之前可用(并可能加载)。

关于JavaScript:JavaScript 什么时候评估一个函数,onload 或什么时候调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2812441/

相关文章:

javascript - 单击特定下拉选项时不要打开 fancybox

jquery - 选择不包含类的 Div - jQuery

android - 使用 map_view (flutter) 处理后退按钮

javascript - selectize.js 远程填充其他输入

javascript - 函数声明 - 函数表达式 - 作用域

php - jquery json选择问题

javascript - 如何使用 javascript 查找字符串中的确切子字符串

jquery - 以编程方式触发 iframe 类型 magnificPopup

jquery-ui - jquery嵌套li点击事件多次调用

android - 在 Android 中保存 map 缩放和位置