简体   繁体   English

可以在浏览器中检查“可用内存”吗?

[英]Possible to check 'available memory' within a browser?

I'm just making up a scenario, but let's say I have a 500MB file that I want to provide an html table for the client to view the data.我只是在编一个场景,假设我有一个 500MB 的文件,我想提供一个 html 表供客户端查看数据。 Let's say there are two scenarios:假设有两种情况:

  • They are viewing it via a Desktop where they have 1.2GB available memory. They can download the whole file.他们通过桌面查看它,其中有 1.2GB 可用空间 memory。他们可以下载整个文件。
  • Later, they try and view this same table on their phone.后来,他们尝试在手机上查看同一张桌子。 We detect that they only have 27MB available memory, and so give them a warning that says "We have detected that your device does not have enough memory to view the entire table. Would you like to download a sample instead?"我们检测到他们只有 27MB 可用空间 memory,因此向他们发出警告:“我们检测到您的设备没有足够的 memory 来查看整个表格。您想下载一个示例吗?”

Ignoring things like pagination or virtual tables, I'm just concerned about "if the full dataset can fit in the user's available memory".忽略诸如分页或虚拟表之类的事情,我只关心“完整数据集是否适合用户的可用内存”。 Is this possible to detect in a browser (even with a user's confirmation).这是否可以在浏览器中检测到(即使有用户的确认)。 If so, how could this be done?如果是这样,如何做到这一点?

Update更新

This answer has been answered about 6 years ago, and the question points to an answer from 10 years ago.这个答案大约6年前就有人回答过, 问题指向10年前的一个答案。 I'm wondering what the current state is, as browsers have changed quite a bit since then and there's also webassembly and such.我想知道当前的 state 是什么,因为从那时起浏览器发生了很大变化,还有 webassembly 等。

Use performance.memory.usedJSHeapSize .使用performance.memory.usedJSHeapSize Though it non-standard and in development, it will be enough for testing the memory used.虽然它是非标准的并且正在开发中,但它足以测试所使用的 memory。 You can try it out on edge/chrome/opera, but unfortunately not on firefox or safari (as of writing).您可以在 edge/chrome/opera 上试用,但遗憾的是不能在 firefox 或 safari(截至撰写本文时)上试用。

Attributes ( performance.memory )属性performance.memory

jsHeapSizeLimit : The maximum size of the heap, in bytes, that is available to the context. jsHeapSizeLimit :上下文可用的堆的最大大小(以字节为单位)。

totalJSHeapSize : The total allocated heap size, in bytes. totalJSHeapSize :分配的总堆大小,以字节为单位。

usedJSHeapSize : The currently active segment of JS heap, in bytes. usedJSHeapSize :JS 堆的当前活动段,以字节为单位。

Read more about performance.memory : https://developer.mozilla.org/en-US/docs/Web/API/Performance/memory .阅读有关performance.memory的更多信息。memory:https://developer.mozilla.org/en-US/docs/Web/API/Performance/memory

CanIUse.com: https://caniuse.com/mdn-api_performance_memory CanIUse.com: https://caniuse.com/mdn-api_performance_memory

CanIUse.com 2020/01/22 CanIUse.com 2020/01/22 可以使用表格图像

I ran into exactly this problem some time ago (a non-paged render of a JSON table, because we couldn't use paging, because :-( ), but the problem was even worse than what you describe:我前段时间遇到了这个问题(JSON 表的非分页渲染,因为我们不能使用分页,因为:-( ),但问题比你描述的更糟糕:

  • the client having 8 GB of memory does not mean that the memory is available to the browser.客户端拥有 8 GB 的 memory 并不意味着浏览器可以使用 memory。
  • any report of "free memory" on a generic device will be, ultimately, bogus (how much is used as cache and buffers?).通用设备上的任何“可用内存”报告最终都是伪造的(有多少用作缓存和缓冲区?)。
  • even knowing exactly "how much memory is available to Javascript" leads to a maintenance nightmare because the translation formula from available memory to displayable rows involves a "memory size for a single row" that is unknown and variable between platforms, browsers, and versions.即使确切地知道“有多少 memory 可用于 Javascript”也会导致维护噩梦,因为从可用 memory可显示行的转换公式涉及“单行的内存大小”,这是未知的,并且在平台、浏览器和版本之间是可变的。

After some heated discussions, my colleagues and I agreed that this was a XY problem .经过一番激烈的讨论,我和同事一致认为这是一个 XY 问题 We did not want to know how much memory the client had, we wanted to know how many table rows it could reasonably and safely display .我们不想知道客户端有多少 memory,我们想知道它能合理安全地显示多少表行

Some tests we ran - but this was a couple of months or three before the pandemic, so September 2019, and things might have changed - showed the following interesting effects: if we rendered off-screen, client-side, a table with the same row, repeated, and random data, and timed how long it took to add each row, this time was roughly correlated with the device performances and limits, and allowed a reasonable estimate of the permissible number of actual rows we could display.我们进行的一些测试——但这是在大流行之前的几个月或三个月,所以是 2019 年 9 月,情况可能已经发生了变化——显示了以下有趣的效果:如果我们在屏幕外、客户端渲染一个具有相同内容的表格行、重复和随机数据,并计时添加每一行所花费的时间,这个时间大致与设备性能和限制相关,并且可以合理估计我们可以显示的实际行数的允许数量。

I have tried to reimplement a very crude such test from my memory, it ran along these lines and it transmitted the results through an AJAX call upon logon:我试图从我的 memory 重新实现一个非常粗略的此类测试,它沿着这些线路运行,并在登录时通过 AJAX 调用传输结果:

var tr = $('<tr><td>...several columns...</td></tr>')
$('body').empty();
$('body').html('<table id="foo">');
var foo = $('#foo');

var s = Date.now();
for (i = 0; i < 500; i++) {
    var t = Date.now();
    // Limit total runtime to, say, 3 seconds
    if ((t - s) > 3000) {
        break;
    }
    for (j = 0; j < 100; j++) {
        foo.append(tr.clone());
    }
    var dt = Date.now() - t;
    // We are interested in when dt exceeds a given guard time
    if (0 == (i % 50)) { console.debug(i, dt) };
}
// We are also interested in the maximum attained value
console.debug(i*j);

The above is a re-creation of what became a more complex testing rig (it was assigned to a friend of mine, I don't know the details past the initial discussions).上面是对更复杂的测试装置的重新创建(它被分配给了我的一个朋友,我不知道最初讨论后的细节)。 On my Firefox on Windows 10, I notice a linear growth of dt that markedly increases around i=450 (I had to increase the runtime to arrive at that value; the laptop I'm using is a fat Precision M6800).在我的 Firefox on Windows 10 上,我注意到 dt 呈线性增长,在 i=450 左右显着增加(我必须增加运行时间才能达到该值;我使用的笔记本电脑是一台胖 Precision M6800)。 About a second after that , Firefox warns me that a script is slowing down the machine (that was, indeed, one of the problems we encountered when sending the JSON data to the client).大约一秒钟后 Firefox 警告我脚本正在减慢机器速度(这确实是我们在将 JSON 数据发送到客户端时遇到的问题之一)。 I do remember that the "elbow" of the curve was the parameter we ended up using.我确实记得曲线的“肘部”是我们最终使用的参数。

In practice, if the overall i*j was high enough (the test terminated with all the rows), we knew we need not worry;实际上,如果整体 i*j 足够高(测试以所有行结束),我们知道我们不必担心; if it was lower (the test terminated by timeout), but there was no "elbow", we showed a warning with the option to continue;如果它较低(测试因超时而终止),但没有“肘部”,我们会显示警告并提供继续选项; below a certain threshold or if "dt" exceeded a guard limit, the diagnostic stopped even before the timeout, and we just told the client that it couldn't be done, and to download the synthetic report in PDF format.低于某个阈值或如果“dt”超过保护限制,诊断甚至在超时前停止,我们只是告诉客户它无法完成,并以 PDF 格式下载综合报告。

You may want to use the IndexedDB API together with the Storage API :您可能希望将IndexedDB API存储 API一起使用:

Using navigator.storage.estimate().then((storage) => console.log(storage)) you can estimate the available storage the browser allows the site to use.使用navigator.storage.estimate().then((storage) => console.log(storage))您可以估计浏览器允许站点使用的可用存储空间。 Then, you can decide whether to store the data in an IndexedDB or to prompt the user with not enaugh storage to downlaod a sample.然后,您可以决定是将数据存储在 IndexedDB 中,还是提示存储空间不足的用户下载样本。

 void async function() { try { let storage = await navigator.storage.estimate(); print(`Available: ${storage.quota/(1024*1024)}MiB`); } catch(e) { print(`Error: ${e}`); } }(); function print(t) { document.body.appendChild(document.createTextNode( t )); }

(This snippet might not work in this snippet context. You may need to run this on a local test server) (此代码段在此代码段上下文中可能不起作用。您可能需要在本地测试服务器上运行它)


Wide Browser Support广泛的浏览器支持

Sort of.有点。

As of this writing, there is a Device Memory specification under development.在撰写本文时,正在开发一个设备 Memory 规范。 It specifies the navigator.deviceMemory property to contain a rough order-of-magnitude estimate of total device memory in GiB;它指定navigator.deviceMemory属性以包含 GiB 中总设备 memory 的粗略数量级估计; this API is only available to sites served over HTTPS. Both constraints are meant to mitigate the possibility of fingerprinting the client, especially by third parties.此 API 仅适用于通过 HTTPS 服务的站点。这两个限制都是为了减少对客户端进行指纹识别的可能性,尤其是第三方。 (The specification also defines a 'client hint' HTTP header, which allows checking available memory directly on the server side.) (该规范还定义了一个“客户端提示”HTTP header,它允许直接在服务器端检查可用的 memory。)

However, the W3C Working Draft is dated September 2018, and while the Editor's Draft is dated November 2020, the changes in that time span are limited to housekeeping and editorial fixups.然而, W3C 工作草案的日期是 2018 年 9 月,而编辑草案的日期是 2020 年 11 月, 但该时间跨度内的更改仅限于内务管理和编辑修正。 So development on that front seems lukewarm at best.因此,这方面的发展充其量似乎不冷不热。 Also, it is currently only implemented in Chromium derivatives .此外,它目前仅在 Chromium 衍生品中实现

And remember: just because a client does have a certain amount of memory, it doesn't mean it is available to you .请记住:仅仅因为客户确实拥有一定数量的 memory,并不意味着可以使用它。 Perhaps there are other purposes for which they want to use it.也许还有其他目的,他们想使用它。 Knowing that a large amount of memory is present is not a permission to use it all up to the exclusion to everyone else.知道存在大量的 memory 并不表示可以使用它直到排除其他人。 The best uses for this API are probably like the ones specified in the question: detecting whether the data we want to send might be too large for the client to handle.这个 API 的最佳用途可能与问题中指定的用途类似:检测我们要发送的数据是否太大而客户端无法处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查浏览器通知是否可用 - Check if browser notification is available 检查浏览器中是否有.click()函数 - check if .click() function is available in browser 是否可以在解构之前检查对象是否可用? - Is it possible to check if the object is available before Destructuring? 浏览器中的JavaScript / jQuery内存使用情况 - JavaScript / jQuery memory usage within a browser 是否可以从浏览器中编辑计算机上的文件? - Is it possible to edit a file on computer from within a browser? 是否可以检查浏览器(JS)中是否安装了扩展程序? - Is it possible to check if an extension is installed on the browser (JS)? 从iframe中获取浏览器窗口的可用高度 - get available height of browser window from within iframes 是否可以在单个JSON消息中将一组图像二进制文件返回给浏览器? - Is it possible to return a set of image binaries within a single JSON message to browser? 是否可以在浏览器视口中获取div的位置?不在文件中。在窗口内 - Is it possible to get the position of div within the browser viewport? Not within the document. Within the window 是否可以使用Javascript(不在浏览器中运行)检查磁盘上是否存在文件? - Is it possible to check if a file exists on disk using Javascript (not running in a browser)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM