Can you write jQuery code in a line before loading jQuery?

I would not think that this is possible at all, but I'm just curious 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'm just wondering, is this really so? Will jQuery accept this block $(function(){}); and make it work after downloading it?

+4
source share
1 answer

No, it does not work as your friend expects, because $ will be undefined at this point, so calling the $ function with argument function(){ } will result in a javascript error indicating that $ undefined. You must download jQuery before trying to use it.

Your friend may be confused, considering that $ is special, but $ is a name like any other. I.e:

 function jQuery(){ // do stuff } 

and

 function $(){ // do stuff } 

will do the same. Having these definitions in an external file will not make them callable until they are loaded.

Tangential note. You cannot write code that will eventually use jQuery before loading jQuery, but you would put your code in something that would be called only after loading jQuery. I don’t know about any jQuery convention about this, as it is not very common in this library, but Facebook does it like this: https://developers.facebook.com/docs/reference/javascript/ I don’t think your friend should actually try to do this while he is no longer familiar with JavaScript.

+12
source

Source: https://habr.com/ru/post/1382055/


All Articles