jQuery $(window).load与window.onload之间的区别

jQuery $(window).load与window.onload之间的区别

问题描述:

我有以下代码:

function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(53.743317, -0.331004),
    zoom: 12
  };
  var map = new google.maps.Map(document.getElementById("map-canvas"),  mapOptions);
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?key={APIKEY}&sensor=false&callback=initialize';
  document.body.appendChild(script);
}

如果我放

$( window ).load(function() {
    loadScript;
});

它不会加载我的地​​图. Google Maps JS中的错误是Uncaught TypeError: Object #<Object> has no method 'Load'.但是,如果我使用

It won't load my map. Error in google maps js is Uncaught TypeError: Object #<Object> has no method 'Load'. However if I use

window.onload = loadScript;

它将很好地加载它.我完全不知道为什么.

It will load it in fine. I have absolutely no idea why.

$(window).load(loadScript());

也可以,只是将其作为调用它的函数而没有.你能告诉我这种现象的原因吗?

Also works, just having it as a function that calls it doesn't. Could you tell me the reason of this behavior?

您实际上并没有在$(window).load()版本中调用loadScript-您刚刚创建了一个"void"表达式,该表达式的计算结果为对该表达式的引用功能.

You haven't actually invoked loadScript in the $(window).load() version - you've just created a "void" expression that evaluates to a reference to that function.

执行以下任一操作

$(window).load(function() {
     loadScript();  // NB: parentheses
})

或:

$(window).load(loadScript);

也就是说,您可能希望使用$(document).ready()而不是$(window).load()

That said, you perhaps want $(document).ready() rather than $(window).load()