A script is executed / not executed due to when jQuery is loaded. Why?

This is the problem I have. Try code :

if (typeof jQuery == 'undefined') {
    function getScript(url, success) {
        var script = document.createElement('script');
        script.src = url;

        var head = document.getElementsByTagName('head')[0];

        done = false;
        script.onload = script.onreadystatechange = function () {
            if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
                done = true;
                success();
                script.onload = script.onreadystatechange = null;
                head.removeChild(script);
            };
        };

        head.appendChild(script);
    };

    getScript('http://code.jquery.com/jquery-1.11.2.min.js', function () {
        if (typeof jQuery !== 'undefined') {
            jQuery(document).ready(function ($) {
                MyFunction($);
            });
        }
    });   
} else {
    jQuery(document).ready(function ($) {
        MyFunction($);
    });
}

function MyFunction($) {
    $.getJSON("http://archiesocial.progettiarchimede.it/widget_privacy/test.aspx?asd=1&callback=?", function (d) {
    }).done(function(d) { 
        JsonToHtml(d);
    });
}    

function JsonToHtml(html) {
    var items = [];
    $.each(html, function (key, val) {
        items.push(val);
    });

    $('body').prepend(items.join(''));
} 

      

you will notice that my code is checking if jQuery is loaded. If not, it downloads the version from an external source; than to get the JSON, parse it and "execute".

As you can see, the script loaded inside the body, it doesn't load at all (that's my problem).

Now try selecting the jQuery version / library in the script (1.8.3 is ok) and hit the play button: you will also see the rendering script /: the script is running !!!

Why loading jQuery first (here) renders the script and loading jQuery later won't execute the script? Can you help me?

+3


source to share


2 answers


I think your best bet is to force the onload event to be discarded if it is already fired, since when jQuery is loaded (if undefined) this event is already fired. This is a workaround:

function JsonToHtml(html) {
    var items = [];
    $.each(html, function (key, val) {
        items.push(val);
    });

    $('body').prepend(items.join(''));
    if (document.readyState === 'complete') { // check if document is complete
        var evt = document.createEvent('Event');
        evt.initEvent('load', false, false);
        window.dispatchEvent(evt); // then redispatch onload event
    }
}

      



-DEMO -

+2


source


I think the problem is the area. The MyFunction () and JsonToHtml () functions are out of scope. (Remember that you are working with async functions like getJSON) My explanation may be wrong, but the code works.: P

You have no problem with this code .



function _test(){}
_test.prototype = {
    hasjQuery: function(){
        if(typeof window.jQuery !='undefined' && !_test.prototype.otherLibrary() ) {
            return true;
        }else{
            return false;
        }
    },
    otherLibrary: function(){
        if (typeof document.$ == 'function') {
            return true;
        }else{
            return false;
        }
    },
    inyectjQuery: function(url, success){
        var script = document.createElement('script');
        script.src = url;
        script.id = "delete";
        done = false;
        script.onload = script.onreadystatechange = function() {
            if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
                done = true;
                success();
                script.onload = script.onreadystatechange = null
            }
        };
        document.getElementsByTagName('head')[0].appendChild(script)
    },
    myFunction: function(){
        urljQuery = 'http://code.jquery.com/jquery-latest.min.js';
        if(_test.prototype.hasjQuery()){
            jQuery.getJSON("http://archiesocial.progettiarchimede.it/widget_privacy/test.aspx?asd=1&callback=?", 
                function (d) {
                    _test.prototype.JsonToHtml(d);
                }).done(function() { 
                    console.log("Success getJSON action");
                });
        }else{
            _test.prototype.inyectjQuery(urljQuery, function(){
                if (typeof window.jQuery == 'undefined') {
                    console.log("unable to load jQuery");
                }else{
                    jQuery.getJSON("http://archiesocial.progettiarchimede.it/widget_privacy/test.aspx?asd=1&callback=?", 
                    function (d) {
                        _test.prototype.JsonToHtml(d);
                    }).done(function() { 
                        console.log("Success getJSON action");
                    });
                }
            });
        }
    },
    JsonToHtml: function(html){
        var items = [];
        jQuery.each(html, function (key, val) {
            items.push(val);
        });

        jQuery('body').prepend(items.join(''));
    }
}
test = new _test();
test.myFunction();

      

-1


source







All Articles