JavaScript - Carga script asincronicamente

 
Vista:
sin imagen de perfil
Val: 5
Ha disminuido su posición en 4 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

Carga script asincronicamente

Publicado por Alejandro (3 intervenciones) el 04/09/2018 22:01:57
Hola,

Tengo este html que carga un simple script que genera un widget mostrando información dentro de un DIV específico.

http://clients.telemet.com/test/

El html carga el script, el script verifica que la pagina tenga jquery cargado, si no lo tiene lo carga, luego via $.ajax (podría utilizar $.getJSON) carga un json y arma un html que carga en el div.

No es gran cosa, pero los json pueden ser pesados y me sería mucho mejor que el script cargara asincrónicamente y no demorar la página, que debo modificar en el script para que cargue de esta manera?

Saludos
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 183
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Carga script asincronicamente

Publicado por Yamil Bracho (78 intervenciones) el 04/09/2018 22:24:28
$_getJSON() retorna una promesa para hacer la llamada asincrona

1
2
3
4
5
6
$.getJSON( "TuURL, {
    format: "json"
})
.done(function( data ) {
      // Procesar data
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 5
Ha disminuido su posición en 4 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

Carga script asincronicamente

Publicado por Alejandro (3 intervenciones) el 04/09/2018 22:33:27
Entonces lo que vuelve a este script sincrónico simplemente es $,ajax()?

Ya hice el cambio de $.ajax a $.getJSON

$.ajax
http://clients.telemet.com/test/

$.getJSON
http://clients.telemet.com/test/index2.html

¿cómo se que el script ya esta cargando asincronicamente?, si veo la consola de carga en ambas paginas no hay diferencia en como se carga.

Saludos y muchas gracias por la respuesta.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 183
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Carga script asincronicamente

Publicado por Yamil Bracho (78 intervenciones) el 04/09/2018 22:43:44
Si, tambien sirve $.ajax, simplemente colocando async en true
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 5
Ha disminuido su posición en 4 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

Carga script asincronicamente

Publicado por Alejandro (3 intervenciones) el 04/09/2018 22:51:56
Hola,

ya implemente la carga asincronica en $.ajax en

http://clients.telemet.com/test/

Pero hay algo raro, en la carga de mi script que retarda todo, alguien que le de una mirada a este script...

http://clients.telemet.com/test/script.js

Gracias
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de xve
Val: 3.162
Oro
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Carga script asincronicamente

Publicado por xve (2100 intervenciones) el 05/09/2018 08:52:42
Hola Alejandro, yo lo veo bien... lo veo un tanto complicado al cargar el jquery desde javascript en vez de cargarlo en la pagina html, pero por el resto lo veo bien...
La carga de los 4 json se me han realizado muy rápido.... sin ningún retardo!!

En vez de hacerlo así:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
(function () {
 
    // Localize jQuery variable
    var jQuery;
 
    /******** Load jQuery if not present *********/
    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.8.2') {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type", "text/javascript");
        script_tag.setAttribute("src",
            "https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js");
        if (script_tag.readyState) {
            script_tag.onreadystatechange = function () { // For old versions of IE
                if (this.readyState == 'complete' || this.readyState == 'loaded') {
                    scriptLoadHandler();
                }
            };
        } else {
            script_tag.onload = scriptLoadHandler;
        }
        // Try to find the head, otherwise default to the documentElement
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    } else {
        // The jQuery version on the window is the one we want to use
        jQuery = window.jQuery;
        main();
    }
 
    /******** Called once jQuery has loaded ******/
    function scriptLoadHandler() {
        // Restore $ and window.jQuery to their previous values and store the
        // new jQuery in our local jQuery variable
        jQuery = window.jQuery.noConflict(true);
        // Call our main function
        main();
    }
 
    /******** Our main function ********/
    function main() {
        jQuery(document).ready(function ($) {
            var baseURL = "https://telemet.xyz/mdz/";
            /******* Load CSS *******/
            var css_link = $("<link>", {
                rel: "stylesheet",
                type: "text/css",
                href: baseURL + "weather_mdz.css"
            });
            css_link.appendTo('head');
 
 
            /******* Load HTML *******/
            $.ajax({
                type: 'GET',
                url: baseURL + 'CURRENT.json',
                async: true,
                dataType: 'json',
                success: function (data) {
                    $('#home-weather-wrapper').html('<div id="home-weather-container"><a href="/pages/clima.html" id="weather-link"><span class="weather-temp">'+data.SAME.Current+'°</span><i class="icon clima-'+data.SAME.Icon+'"></i></a></div>');
                }
            });
 
        });
    }
 
})();  // We call our anonymous function immediately


Yo hubiera cargado el jquery en la web y le abría pasado por parámetro a la función anónima... algo así:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<script>
(function (jQuery) {
 
    /******** Called once jQuery has loaded ******/
    function scriptLoadHandler() {
        // Restore $ and window.jQuery to their previous values and store the
        // new jQuery in our local jQuery variable
        jQuery = window.jQuery.noConflict(true);
        // Call our main function
        main();
    }
 
    /******** Our main function ********/
    function main() {
        jQuery(document).ready(function ($) {
            var baseURL = "https://telemet.xyz/mdz/";
            /******* Load CSS *******/
            var css_link = $("<link>", {
                rel: "stylesheet",
                type: "text/css",
                href: baseURL + "weather_mdz.css"
            });
            css_link.appendTo('head');
 
            /******* Load HTML *******/
            $.ajax({
                type: 'GET',
                url: baseURL + 'CURRENT.json',
                async: true,
                dataType: 'json',
                success: function (data) {
                    $('#home-weather-wrapper').html('<div id="home-weather-container"><a href="/pages/clima.html" id="weather-link"><span class="weather-temp">'+data.SAME.Current+'°</span><i class="icon clima-'+data.SAME.Icon+'"></i></a></div>');
                }
            });
        });
    }
 
})(window.jQuery);  // We call our anonymous function immediately
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar