javascriptperformanceoptimizationyepnope

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'
  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. This process takes about 1.5s which is really long for the user to wait.

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

Solution

  • Why do you have the scripts as textual arrays in your html page?

    I would have stored them as .json files on the server.

    $.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.