How to make this variable global?

0

I'm using this script to check for support for webp images but I'm having trouble setting the type, here's the code that checks:

hasWebP = (function() {
    var images = {
        basic: "data:image/webp;base64,UklGRjIAAABXRUJQVlA4ICYAAACyAgCdASoCAAEALmk0mk0iIiIiIgBoSygABc6zbAAA/v56QAAAAA==",
        lossless: "data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="
    };

    return function(feature) {
        var deferred = $.Deferred();

        $("<img>").on("load", function() {
            if(this.width === 2 && this.height === 1) {
                deferred.resolve();
            } else {
                deferred.reject();
            }
        }).on("error", function() {
            deferred.reject();
        }).attr("src", images[feature || "basic"]);

        return deferred.promise();
    }
})();

hasWebP().then(function() {
    tipo = "webp";
}, function() {
    tipo = "jpg";
});
console.log(tipo);

But when I call the variable tipo out of this function it is given as undefined .

I've tried to create it so window.tipo but it also did not work, how can I solve this problem?

    
asked by anonymous 07.04.2017 / 18:08

1 answer

3
  

... When I call the type variable outside this function it is given as undefined .

The problem is not whether the variable is global or not, but rather the time when the value is assigned. It is no use wanting to capture the value of a globally defined variable at the same time, and you define values in it by asynchronous events.

For the best understanding, you need to understand that the promise is asynchronous and therefore the values are not defined immediately in the global scope, but after a certain time.

My solution to this would be to use a callback to be able to correctly get the value you are setting in tipo .

function usarTipo(tipo) {
     console.log(tipo);
}


hasWebP().then(function() {
     usarTipo("webp");
}, function() {
    usarTipo("webp");
});

The advantage of the callback is that it will perform the functionality only when it is called within the result of the promise.

Your problem is pretty much the same as described in this question:

  

I have tried to create it so window.type but also did not work

You do not have to save this in a global variable since the value's definition is being executed in scope that is "in another timeline".

I stress that the best solution in your case is to try to work with callbacks that can be called independent of time than requests for asynchronous processes.

    
07.04.2017 / 18:27