Javascript数组操作:有更好的方法来完成以下操作吗?

3
我有以下代码,它的功能是:
  1. 从页面上的元素中获取文本
  2. 过滤出特定的元素
  3. 按 '\n' 分割
  4. 删除数组中所有的空白元素

这似乎比我想象的要花费更多的时间,并且不能删除数组中填充了空格的所有元素。

仅供参考,我将两个数组合并成一个,并使用YepNope加载脚本和样式。这个过程需要1.5秒,对于用户来说等待时间太长了。

如何提高速度?

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);
                }
        }}]);
1个回答

2

你为什么要在html页面中将脚本存储为文本数组?

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

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

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

做了一些微小的改动,但喜欢外部JSON文件的想法。好主意...我的想法在脑海中看起来还不错,但实践起来很糟糕。 - Mike Fielden

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接