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

时间:2011-04-13 15:18:12

标签: javascript performance optimization yepnope

我有以下代码:

  1. 从页面上的元素中抓取文本
  2. 特定元素的过滤器
  3. 分拆'\ n'
  4. 删除数组中所有空白元素
  5. 这似乎比我想要的时间多一点,并没有像你期望的那样删除阵列中所有空格填充的元素。

    仅供参考我然后将两个数组合并为一个并使用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 个答案:

答案 0 :(得分:2)

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

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

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

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

相关问题