2011-04-13 55 views
3

我有以下代码的作用:JavaScript数组操作:是否有更好的方法来执行以下操作?

  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); 
       } 
     }}]); 

回答

2

为什么你的脚本作为文本数组在你的html页面?

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

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

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

+0

它有点不同,但喜欢外部JSON文件的想法。好主意......我的想法在我的脑海里似乎很好,在实践中很糟糕。 – 2011-04-13 21:01:08

相关问题