简体   繁体   English

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

[英]Javascript array manipulation: Is there a better way to do the following?

I have the following code which does: 我有以下代码:

  1. Grabs text from an element on the page 从页面上的元素中抓取文本
  2. Filters for the particular element 特定元素的过滤器
  3. Splits on the '\\n' 拆分'\\ n'
  4. Removes all elements of the array that are white space 删除数组中所有空白元素

This seems to take a little more time than I'd like and doesn't remove all the whitespace filled elements of the array, as you might expect. 这似乎比我想要的时间多一点,并没有像你期望的那样删除数组的所有空格填充元素。

Just for reference I then combine the two arrays into one and load the scripts and styles using YepNope. 仅供参考,然后将两个数组合并为一个,并使用YepNope加载脚本和样式。 This process takes about 1.5s which is really long for the user to wait. 这个过程需要大约1.5秒,这对用户来说真的很长。

How can I improve the speed of this? 我怎样才能提高速度呢?

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

Why do you have the scripts as textual arrays in your html page? 为什么在html页面中将脚本作为文本数组?

I would have stored them as .json files on the server. 我会将它们存储为服务器上的.json文件。

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

If you don't want them to be static then set up some routing and server json files based on incoming URL. 如果您不希望它们是静态的,那么根据传入的URL设置一些路由和服务器json文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM