How to include jQuery library in single js file wi

2019-08-02 14:04发布

3rd party websites can place my script tag on their websites, like so on for example ExternalSite.html in the head section:

<script type="text/javascript">
(function () {
    var ttScript = document.createElement('script'); ttScript.async = true;
    ttScript.src = '//www.example.com/script/myscript.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ttScript);
})();
</script>

On my own server, in the file myscript.js I have this code:

$.ajax({
    url: "http://www.example.com/iplookup.php",
    data: null,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp'
}).done(function (json) {
    self.ip = json;
});

But once a user visits the 3rd party site, on the first line here I get Uncaught ReferenceError: $ is not defined

Now this is probably because I don't reference jQuery on the 3rd party site, where I include the myscript.js file. The problem is that:

  1. I do not know if this 3rd party site even has jQuery running
  2. I don't know how to reference jQuery from myscript.js, also without possibly interfering with an existing jQuery reference on the 3rd party site

1条回答
甜甜的少女心
2楼-- · 2019-08-02 14:49

First make a check for jQuery load using javaScript

    window.onload = function() {
        if (window.jQuery) {
            // jQuery is loaded  
            // Now insert your scripts        
        } else {
            // jQuery is not loaded
            // Load it manually from any cdn e.g., //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js        
        }
    }

There are some other similar ways of checking which we can use

    if (typeof jQuery != 'undefined') {
        // jQuery is loaded  
    } else {
        // jQuery is not loaded
    }

    if (jQuery) {
        // jQuery is loaded  
    } else {
        // jQuery is not loaded
    }

There 's a working fiddle available by atornblad which also tells the time jQuery took to load.

You can have a look for a better reference.

Hope this helps..

查看更多
登录 后发表回答