Javascript 防止重复的$.ajax({dataType:'script'})导致内存泄漏

Javascript 防止重复的$.ajax({dataType:'script'})导致内存泄漏,javascript,jquery,performance,memory-leaks,dynamic-script-loading,Javascript,Jquery,Performance,Memory Leaks,Dynamic Script Loading,我正在编写一个本地运行的小web应用程序,希望能够间歇性地访问网络。考虑到这一点,我正在检查外部依赖项Google Maps是否无法加载,并在10秒后重试。简要概述: // Assume the worst var mapsSuccess = false; // Only gets invoked by maps success function initialize(){ // Set the flag to prevent continuous recursion of the pre

我正在编写一个本地运行的小web应用程序,希望能够间歇性地访问网络。考虑到这一点,我正在检查外部依赖项Google Maps是否无法加载,并在10秒后重试。简要概述:

// Assume the worst
var mapsSuccess = false;

// Only gets invoked by maps success
function initialize(){
  // Set the flag to prevent continuous recursion of the previous function
  mapsSucess = true;

  /* application init */
}

// Invoke immediately
( function mapsCall(){
  // Maybe we don't need this...
  if( mapsSuccess === true ){
    return;
  }

  $.ajax( {
    cache    : true,
    dataType : 'script',
    // `callback` param specifies function to call on successful execution
    url      : googleMapsUri + '&callback=initialize'
  } );

  // Run this function again in 10 seconds to see if we succeeded
  setTimeout( mapsCall, 10000 )
}() );
问题是在最坏的情况下,我们无法在数小时内成功加载地图。存在回退脱机内容,但当前内存泄漏最终会导致浏览器崩溃。检查Chrome开发工具中的时间线,其来源显而易见:

每次重新调用mapsCall时,都会调用新的DOM节点和新的事件侦听器。我想删除这些并删除绑定的任何事件侦听器具有讽刺意味的是,我的代码没有设置任何事件侦听器,因此我在mapsCall主体中设置了以下内容:

这可以有效地删除冗余的脚本元素,但不会因为事件侦听器计数而真正减少内存泄漏。我尝试使用$.\u数据元素“events”嗅探这些神秘的事件侦听器绑定在何处,但它们不在脚本本身、文档、窗口或根元素html正文中,所以我不知所措

$( 'script[async][src*="callback=initialize"]' ).off().remove();