最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can you write jQuery code inline before loading jQuery? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Nov 19, 2011 at 17:07 trusktrtrusktr 45.6k58 gold badges210 silver badges287 bronze badges 3
  • 7 Well, does it? It is on a live page, you say... – GolezTrol Commented Nov 19, 2011 at 17:09
  • Yeah, after testing, it didn't work. I guess I really wanted to see if I could get an answer faster here or by testing... Yeah i know that's shady! But I was able to test faster. I'll avoid such questions in the future. – trusktr Commented Nov 19, 2011 at 17:56
  • This issue happens often enough it's handy to have a question like this to point people at. – T.J. Crowder Commented Apr 8, 2017 at 12:39
Add a ment  | 

1 Answer 1

Reset to default 12

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 mon to do that with this library, but Facebook does it like this: https://developers.facebook./docs/reference/javascript/ I don't think your friend should actually attempt this until he is more familiar with JavaScript.

发布评论

评论列表(0)

  1. 暂无评论