Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

jquery - Defer loading of JavaScript - Uncaught ReferenceError: $ is not defined

I use google code to defer loading javascript (google pages)

But I have some inline javascripts such as:

<script type="text/javascript">
$(function () {
    alert("please work");
});
</script>

And this gives me:

Uncaught ReferenceError: $ is not defined

I think I need some function, which was triggered after jQuery was loaded and init my inline javascripts. But if there is another way, I will be glad.

EDIT:

Some of you are completely out of topic. Mahesh Sapkal was close.

With this code I have no error, but still don't work

<head>
    <script type="text/javascript">
        var MhInit = NULL;

        // Add a script element as a child of the body
        function downloadJSAtOnload() {
            var element = document.createElement("script");
            MhInit = element.src = "my_packed_scripts.js";
            document.body.appendChild(element);
        }

        // Check for browser support of event handling capability
         if (window.addEventListener)
            window.addEventListener("load", downloadJSAtOnload, false);
         else if (window.attachEvent)
             window.attachEvent("onload", downloadJSAtOnload);
         else window.onload = downloadJSAtOnload;
    </script>

</head>
<body>
    <script type="text/javascript">
        MhInit.onload = function() {
            console.debug("here");
        };
    </script>
</body>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot use jQuery before it is loaded. If you move the <script src="jquery.js" /> at the bottom of your page you must also move all the lines that use $(...) below it.

There is a tricky solution that goes something along these lines:

1) Defining few variables at the top of your page:

var _jqq = [];
var $ = function(fn) {
    _jqq.push(fn);
};

2) In the middle of the page you can write:

$(function() {
    alert("document ready callback #1");
});
$(function() {
    alert("document ready callback #2");
});

3) At the bottom of your page, include jQuery:

<script src="//code.jquery.com/jquery.min.js"></script>

4) And finally:

$(function() {
    $.each(_jqq, function(i, fn) {
        fn();
    });
});

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...