简体   繁体   中英

jquery not loading in a script from another domain

I have the problem that I want to load a Javascript on a website from another website and use jQuery there. But it seems jQuery is never available. I tried all the things in this post: Test if jquery is loaded not using the document ready event .

Is it maybe a security cross site issue?

Here is the page: Japanese cities

jQuery is loaded here in line 29

<script src="/cache/template/gzip.php?jquery.min-3eab6f02.js" type="text/javascript"></script>

The script is loaded in line 343

    <script type="text/javaScript" src="http://www.factfish.com/api/js/japanese_cities.js"></script>

To narrow it down I just used an empty $ajax function

(function() {
if (jQuery) {
    $.ajax({});
}
})();

I always get the error

TypeError: $.ajax is not a function

Any ideas?

Thank you

Bernhard

In your page there's

<script src="/cache/template/gzip.php?jquery-noconflict-4baa84c1.js" type="text/javascript"></script>

which does this:

jQuery.noConflict();

This means you

Relinquish jQuery's control of the $ variable

Ie $ is no longer associated with jQuery, and you must explicitly use jQuery instead.

See this: https://api.jquery.com/jquery.noconflict/

This should work:

(function() {
    if (jQuery) {
        jQuery.ajax({});
    }
})();

Another way to do this:

(function( $ ) {
  $(function() {

    // More code using $ as alias to jQuery
    $.ajax({});

  });
})(jQuery);

As pointed out by @dekkard , you have effectively erased the $ shortcut alias for jQuery.

As an alternative to the IIFE's shown by @dekkard , There is also a shortcut DOM ready that combines document.ready with a locally scoped $

eg

jQuery(function($){
    // Your DOM ready code - using a locally scoped $
});

"Half the code, twice the flavour!" :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM