Artist cover update generates many requests

Asked

Viewed 110 times

0

I have the following code snippet:

var musica_atual = '';
var capasplit = '';

function checaURL(endereco){

    var http = new XMLHttpRequest();

    http.open('HEAD', endereco, false);
    http.send();

    return http.status != 404;

}   

// Atualiza os nomes das musicas
function atualiza_nome_musica() {
    $.ajax({
        url : 'http://somdomato.com:8000/stats?sid=1&json=1',
        dataType : 'jsonp',
        timeout : '4000',
        success: function(data) {
            if (data && data.songtitle) {
                musica_atual = data.songtitle || '';
                capasplit = musica_atual.split('-');

                // testa se tem locutor ao vivo
                if (musica_atual.substr(0, 7) === 'Ao Vivo') {
                    $('#pedidos_ativos').hide();
                    $('#pedidos_desativados').show();
                    $('.aovivo').show();
                    $('.proximas').hide();

                    // busca foto do locutor
                    var aux = musica_atual.split('-');

                    if (aux[1]) {
                        var nome_locutor = $.trim(aux[1]);
                        var musica_limpa2 = musica_atual.substr(musica_atual.indexOf("-") + 1);
                        var musica_atual = musica_limpa2.substr(musica_limpa2.indexOf("-") + 1);

                        $('#foto_locutor').attr('src', 'img/locutores/'+nome_locutor+'.jpg').load(function() {
                            $(this).show();
                        });
                    }
                } else {
                    $('.aovivo').hide();
                    $('.proximas').show();
                    $('#pedidos_ativos').show();
                }

                    $('#nome_musica').html( musica_atual );
                    $('#nome_locutor').html( nome_locutor );
            }
        }
    });     

    if (capasplit[0] != '') {
        $.getJSON("https://ajax.googleapis.com/ajax/services/search/images?callback=?", {
            q: '"' + capasplit[0] + '"',
            v: '1.0'
        }, function(data) {
            capa_nova = data.responseData.results[0].url;

            if (checaURL(capa_nova)) {
                $('#capa_musica').html('<img src="' + data.responseData.results[0].url + '">');
            } else {
                $('#capa_musica').html('<img src="/img/player/violao.png">');
            }

        });
    } else {
        $('#capa_musica').html('<img src="/img/player/violao.png">');
    }

}

atualiza_nome_musica();
setInterval(atualiza_nome_musica, 10000);

Everything works perfect, the problem is that seeking a new cover every 10 seconds generates a certain LAG and some people have complained that the radio is crashing.

And the checaURL function is generating this error: XMLHttpRequest cannot load http://www.cottagespot.com/images/no-image-large.png. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://somdomato.com' is therefore not allowed access.

How can I prevent that from happening?

2 answers

1


@Lucas, unfortunately you cannot use CORS to check if the image URL exists. In this case you will need to replace the following snippet of your code:

capa_nova = data.responseData.results[0].url;
if (checaURL(capa_nova)) {
    $('#capa_musica').html('<img src="' + data.responseData.results[0].url + '">');
} else {
    $('#capa_musica').html('<img src="/img/player/violao.png">');
}

by the following:

var capa = document.getElementById("capa_musica");
var capa_nova = data.responseData.results[0].url;
var capa_default = "/img/player/violao.png";

capa.src = capa_default;
var img_nova = new Image();
img_nova.onload = function() {
    capa.src = img_nova.src;
}
img_nova.src = capa_nova;

Note that in this case I am not adding a new <img>, then the ID #capa_musica should belong to an existing cover.

In the above example, the script is always assigning the default image to the tag <img id="capa_musica">, if you can upload the image obtained by google, it will update the <img id="capa_musica">.

var capa = document.getElementById("capa");
var imgURL = "http://3.bp.blogspot.com/-F7KGPjHrFP4/TvitGj30SJI/AAAAAAAADpQ/j-gyevUaevc/s1600/capa.jp";

window.setTimeout(function () {
    var img = new Image();
    img.onload = function() {
        capa.src = img.src;
    }
    img.src = imgURL;
}, 1000);
#capa {
    width: 250px;
    height: 250px;    
}
<img id="capa" />

  • Friend, thank you very much for the answer, I will test and put here the result.

  • It worked! Thank you!!!

1

This error generated by Xmlhttprequest informs that you cannot make the request in the informed domain, in this case, cottagespot.com, this is by default the operation of the web, it is only possible to make requests in your own domain or in domains that have released external access, or for other Ips or for global access, in which case, the website owner must release access to your domain or provide an API for consultation.

  • taking into account that he is asking a random image on Google. I find it difficult to use CORS to download the images.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.