Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you write jQuery code inline before loading jQuery?

I wouldn't think its possible at all, but I'm just wondering because my friend has this on his page:

<html>
    <head></head>
    <body>
        <script>
            $(function(){
              // ...
            });
        </script>
        <div><span>html stuff</span></div>
        <script src="jquery-1.7.js"></script>
    </body>
</html>

So I was just wondering, is that valid? Will jQuery take that $(function(){}); block and make it work after its done loading?

like image 216
trusktr Avatar asked Dec 16 '22 07:12

trusktr


1 Answers

No it doesn't work like your friend expects it to because $ will be undefined at that point so calling the function $ with the argument function(){ } will cause a javascript error stating that $ is undefined. You must load jQuery before trying to use it.

Your friend might be confused into thinking that $ is special, but $ is a name like any other. I.e:

function jQuery(){
 // do stuff
}

and

function $(){
  // do stuff
}

would do the exact same thing. Having those definitions in an external file would not make them callable before they were loaded.

Tangental note: It is not strictly impossible to write code that eventually will use jQuery before jQuery has loaded, but you would be putting your code in something that would be called only once jQuery has loaded. I'm not aware of any jQuery convention of doing this, as it's not very common to do that with this library, but Facebook does it like this: https://developers.facebook.com/docs/reference/javascript/ I don't think your friend should actually attempt this until he is more familiar with JavaScript.

like image 180
Kit Sunde Avatar answered Jan 30 '23 22:01

Kit Sunde