Javascript 数组操作 : Is there a better way to do the following?

标签 javascript performance optimization yepnope

我有以下代码:

  1. 从页面上的元素中抓取文本
  2. 过滤特定元素
  3. 在 '\n' 处拆分
  4. 删除数组中所有的空白元素

这似乎比我希望的要多花一点时间,并且不会像您预期的那样删除数组中所有空白填充的元素。

仅供引用,然后我将两个数组合并为一个并使用 YepNope 加载脚本和样式。这个过程大约需要 1.5s,用户等待的时间确实很长。

我怎样才能提高这个速度?

var $containerHtml = $(html);

    // Add the scripts
    scriptArray = $.grep($containerHtml.filter('#includeScripts').text().split('\n'), function (element, index) {
                    return element !== "" && element !== " ";
                });
    // Add the styles
    styleArray = $.grep($containerHtml.filter('#includeStylesheets').text().split('\n'), function (element, index) {
                    return element !== "" && element !== " ";
                });

    // Combine the two arrays into 1
    combinedArrays = scriptArray.concat(styleArray);

    // Load the scripts and styles 
    yepnope([{
        load: combinedArrays,
        callback: function (url, result, key) {
                if (window.console && window.console.firebug) {
                    console.log("Loaded " + url);
                }
        }}]);

最佳答案

为什么在您的 html 页面中将脚本作为文本数组?

我会将它们存储为服务器上的 .json 文件。

$.when($.getJSON("url/script.json"), $.getJSON("url/stylesheet.json")).then(function(script, style) {
    var arr = ...; // combine script & style. 
    yepnope(...);
});

如果您不希望它们是静态的,那么可以根据传入的 URL 设置一些路由和服务器 json 文件。

关于Javascript 数组操作 : Is there a better way to do the following?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5651600/

相关文章:

python - 高效处理 300 万个 Pandas 数据框行

javascript - TypeScript:SyntaxError:控制台中出现 "Unexpected token"消息

java - 自动检查 Web 应用程序的更新

c++ - bool 数组上的原始循环比变换或 for_each 快 5 倍

ruby-on-rails - 加快从 Rails 应用程序下载 19,000 条记录

c - 优化下三角矩阵转置

mysql - 使用mysql时 `join`是否每次都生成笛卡尔积?

javascript - firebase.getDatabase()).ref() 不是函数

javascript - 使用 javascript 将带有数组的表单转换为逗号分隔的查询字符串,且不重复

javascript - Node.js 和 mssql 基于 JSON 动态填充表