问题描述:

Hello i need to build a 3rd Party Widgets with JavaScript and php.

This Widgets will need to use in jQuery and jQuery UI and maybe in the future other jQuery Libraries and Plugins.

so when my client put this Widget to his site i need to know if jQuery and jQuery UI is already loaded and if not load it my self.

I built something but it not working.

 <script>

if (typeof jQuery == 'undefined') {

// jQuery is not loaded

//alert('jQuery is not loaded');

var script = document.createElement('script');

script.type = "text/javascript";

script.src = "http://code.jquery.com/jquery-1.9.1.js";

document.getElementsByTagName('head')[0].appendChild(script);

var script_ui = document.createElement('script');

script_ui.type = "text/javascript";

script_ui.src = "http://code.jquery.com/ui/1.10.3/jquery-ui.js";

document.getElementsByTagName('head')[0].appendChild(script_ui);

} else {

// jQuery is loaded

//alert('jQuery is loaded');

if (typeof jQuery.ui !== 'undefined') {

// ui plugin exists

alert('ui plugin exists');

} else {

// ui plugin DOES NOT exist

//alert('ui plugin DOES NOT exist');

var script_ui = document.createElement('script');

script_ui.type = "text/javascript";

script_ui.src = "http://code.jquery.com/ui/1.10.3/jquery-ui.js";

document.getElementsByTagName('head')[0].appendChild(script_ui);

}

}

</script>

This working fine but when i try to work with jQuery datepicker i get ReferenceError: jQuery is not defined.

 <script>

jQuery(document).ready(function() {

// Handler for .ready() called.

jQuery(function() {

jQuery( "#datepicker" ).datepicker();

});

});

</script>

Even without the jQuery(document).ready(function() It does not work

Please Hellp...

网友答案:

This should do the trick if I understood the problem correctly, the jQuery() function is only defined if already loaded.

if (jQuery) { //jQuery is loaded }

You can do this for the functions you need whether its jQuery, jQuery-ui or something else.

网友答案:

By the time

<script>
jQuery(document).ready(function() {
    // Handler for .ready() called.
    jQuery(function() {
        jQuery( "#datepicker" ).datepicker();
    });
});
</script>

is reached, jQuery may not necessarily be done loading, the browser then doesn't know what do do with it, tries to execute it and tells you "I have no idea what jQuery is". If you call the same block of code again later though, it should work fine.

The simplest way to get around this is to put your $(document).ready() event handler into a separate .js script and include that script in your header, that way jQuery gets to call the event handler whenever it is ready, not the other way around. I created a fiddle to demonstrate this: http://jsfiddle.net/Cjv2k/4/

网友答案:

You can loop until the jQuery object is valid using this:

var checkJQ = setInterval(function() {
    if(jQuery) {
        console.log('jQuery loaded');
        clearInterval(checkJQ);
    }
}, 300);
相关阅读:
Top