【问题标题】:jQuery $.getScript() script accumulation?jQuery $.getScript() 脚本积累?
【发布时间】:2017-05-31 07:02:38
【问题描述】:

我在“页面”中替换来自MySQL(通过 php)的 div 的 html 内容,有时但不总是从MySQL 插入使用$.getScript() 的该内容所需的任何 javascript。

这一切正常。当用户单击next page 时,它会从MySQL 获得新的html 和javascript,但是在许多页面之后它已经积累了许多脚本,这对我来说似乎是个坏主意,因为我不希望脚本不再需要浮动。如果用户单击“上一页”按钮,它们可以重新加载(然后会发生什么 - 同一脚本的多个实例?)。

这些脚本获取包含约 100 个元素的数据数组的音频内容 (ion.sound)。 似乎没有办法删除这些脚本并释放内存。

我担心最终的性能问题。或者这是完全错误的做法?

任何帮助表示赞赏。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

这可能不适用于 getScript 功能。原因是一般来说,项目在加载后会被添加到全局命名空间中。这个question已经有很好的讨论了

根据这些建议,您可以加载脚本,并将差异保存在全局命名空间中,当您删除脚本时,只需再次从全局命名空间中删除这些对象。

这里的示例在您单击按钮时加载 jQuery,然后检查对全局窗口对象进行了哪些更改,并在删除时再次从窗口对象中删除这些项目。

const jQueryId = "#jQuery-loaded-js-id";

function addJQuery( cb ) {
  if (document.querySelector(jQueryId)) {
    console.info('JQuery already loaded');
    return;
  }
  var scriptElem = document.createElement('script');
  scriptElem.id = jQueryId.substr(1);
  scriptElem.addEventListener('load', function( windowKeys, e ) {
    console.log( 'jQuery loaded' );
    // get the difference of keys between before load and after load
    // this will only work if no other scripts were loaded in between
    // which would mean, scripts should only be loaded one at the time
    var newKeys = Object.keys( window );
    var diff = newKeys.reduce( (set, item) => {
      if (windowKeys.indexOf(item) === -1) {
        set.push( item );
      }
      return set;
    }, []);
    scriptElem.dataset.globalKeys = diff;
  }.bind(this, Object.keys(window)) );
  scriptElem.src = 'https://code.jquery.com/jquery-2.2.4.min.js';
  document.body.appendChild( scriptElem );
}

function isJQueryAvailable() {
  // checks if jQuery exists
  alert( !!(window.jQuery || window.$) );
}

function removeJQuery() {
  var elem;
  if (!( elem = document.querySelector(jQueryId) )) {
    console.info('not available');
    return;
  }
  document.body.removeChild(elem);
  // removes any of the global keys added to the DOM
  var keys = elem.dataset.globalKeys.split(',');
  for (let i = 0; i < keys.length; i++) {
    delete window[keys[i]];
  }
  console.info('JQuery removed');
}
<button type="button" onclick="addJQuery()">Get JQuery</button>
<button type="button" onclick="isJQueryAvailable()">Does JQuery Exist?</button>
<button type="button" onclick="removeJQuery()">Remove JQuery</button>

该示例不应该是您真正需要实现的,因为它过于简化了脚本加载时可能发生的情况。可能您需要考虑更多基于模块的方法,您加载的脚本可以自行dispose。我只是给你一个潜在方法的例子

【讨论】:

    【解决方案2】:

    似乎脚本在调用 $.getScript() 后不会挂起,因为它会加载脚本然后执行它。我采用了一种简单的机制来计算脚本,并且每个页面的数量都不同,但不会累积 - 我认为。反正我会犯错。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多