2011-04-13 51 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

相關問題