Q:

Undefined variable error in Javascript

I have written a function in which I read and display in an excel like spread sheet (used the spreadJS library) on a tab. Although it works fine on Ubuntu Chromium, when I run it on Firefox or Chrome I get an error message:
TypeError: spread is undefined
var metricsSheet = spread.getActiveSheet();

This is the function:
    requirejs.config({
        shim: {
            "spreadjs": {
                deps: ["jquery"],
            }
        },
        paths: {
            "jquery": "http://code.jquery.com/jquery-1.9.1.min",
            "spreadjs": "http://cdn.wijmo.com/spreadjs/jquery.wijmo.wijspread.3.20143.15.min",
        },
    });
    require(["jquery", "spreadjs"], function () {
            $("#ss").wijspread();
            spread = $("#ss").wijspread("spread");  
    });

     function initExcel(){
        $(document).ready(function() {

            $.ajax({
                type: "GET",
                url: "Code/python/csv/outputMetrics.csv",
                dataType: "text",
                success: function(data){ // on succes loop through the lines of CSV

                // and pass data into spread sheet.
                    var allLines = data.split('\n');
                    var metricsSheet = spread.getActiveSheet();
                    // set column width of columns
                    metricsSheet.setColumnWidth (1,400);
                    metricsSheet.setColumnWidth (2,300);
                    for (var i=0; i<allLines.length; i++) {
                        var data = allLines[i].split(';');
                        metricsSheet.setValue(i+1, 1, data[0]);
                        metricsSheet.setValue(i+1, 2, data[1]);
                    }
                    spread.isPaintSuspended(false);
                },
                error: function(){
                    alert("Error reading CSV or passing data to Excel");
                }
            });
        });
    }

What can it be the reason that Javascript shows this error?

A:

Most likely you're seeing timing problems, and your code inside initExcel is executed before spread is loaded and created. There's absolutely no guarantee that spread will be available before you need it; it all depends on luck, network speeds and caching.
Define any code which has dependencies inside the require block which ensures its dependencies are met:
require(["jquery", "spreadjs"], function () {
        $("#ss").wijspread();
        var spread = $("#ss").wijspread("spread");  

        function initExcel(){ ... }
});

