Defer loading of JavaScript - Uncaught ReferenceError: $ is not defined
Asked Answered
M

5

3

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>
Morrissey answered 9/1, 2014 at 6:56 Comment(1)
use jQuery.noConflict();Ofilia
W
6

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

Warnke answered 9/1, 2014 at 7:21 Comment(1)
this looks pretty awesome and simple, i'm still testing it though, will update soonKithara
M
2

If you are going to implement async loading of Javascripts, then it would be a better idea to not have inline Javascript which depends on the asynchronously loaded file.

I suspect that you are loading jQuery asynchronously, i.e. after the DOM content has loaded, so any inline scripts in your DOM dependent on jQuery will fail. In that case, you may want to use something like RequireJS to manage your JS dependencies, and load them asynchronously.

However, if you want to go for a simpler solution, I would suggest putting your JS libraries at the end of the DOM, and binding any dependencies to an onload handler.

Something like this

<body>
    <!-- Body content -->
    <script>document.onload = function() { //use jQuery here }</script>
</body>
<script src="/path/to/jQuery/"></script>
Multiplicand answered 9/1, 2014 at 7:6 Comment(2)
tried this with no avail. should this work for a deferred jQuery ?Prepositor
What do you mean by deferred jQuery?Multiplicand
H
2

Since you are deferring loading of jquery, your inline javascript should only be called when jquery has finished loading. Use the following code, to check if the library was loaded.

var scriptElem = document.createElement("script");

scriptElem.onload = function() {
    alert('please work');
};

scriptElem.src = "http://code.jquery.com/jquery-1.10.1.min.js";

document.getElementsByTagName("head")[0].appendChild(scriptElem);
Histone answered 9/1, 2014 at 7:14 Comment(0)
Q
0

when i want defer load jquery, i use like that:

on header

<script> var callBackSomething = [];</script>

after < /body> tag

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

in main.js

if (typeof callBackSomething !== 'undefined' && $.isArray(callBackSomething )){
    $.each(callBackSomething , function (k, v) {
        if($.isFunction(v))
            v();
    });
}

and in page

let js_callback = function () {
// code jquery in here
};
callBackSomething.push(js_callback);
Quitrent answered 27/7, 2018 at 3:0 Comment(0)
B
-3

try this http://w3schools.com/jquery/default.asp. you can easily do that.

<script>
$(document).ready(function(){
$("p").click(function(){
alert("please work");
});
});
</script>
Barbrabarbuda answered 9/1, 2014 at 7:11 Comment(1)
$ is undefined. You can't call $ to delaying loading of JS until $ is available.Churchwoman

© 2022 - 2024 — McMap. All rights reserved.