How to add jQuery in JS file

后端 未结 19 757
星月不相逢
星月不相逢 2020-12-04 05:47

I have some code specific to sorting tables. Since the code is common in most pages I want to make a JS file which will have the code and all the pages using it can referen

19条回答
  •  旧时难觅i
    2020-12-04 06:16

    You can use the below code to achieve loading jQuery in your JS file. I have also added a jQuery JSFiddle that is working and it's using a self-invoking function.

    // Anonymous "self-invoking" function
    (function() {
        var startingTime = new Date().getTime();
        // Load the script
        var script = document.createElement("SCRIPT");
        script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
        script.type = 'text/javascript';
        document.getElementsByTagName("head")[0].appendChild(script);
    
        // Poll for jQuery to come into existance
        var checkReady = function(callback) {
            if (window.jQuery) {
                callback(jQuery);
            }
            else {
                window.setTimeout(function() { checkReady(callback); }, 20);
            }
        };
    
        // Start polling...
        checkReady(function($) {
            $(function() {
                var endingTime = new Date().getTime();
                var tookTime = endingTime - startingTime;
                window.alert("jQuery is loaded, after " + tookTime + " milliseconds!");
            });
        });
    })();

    Other Option : - You can also try Require.JS which is a JS module loader.

提交回复
热议问题