admin 管理员组文章数量: 1086019
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?
- 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
1 Answer
Reset to default 12No 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.
本文标签: javascriptCan you write jQuery code inline before loading jQueryStack Overflow
版权声明:本文标题:javascript - Can you write jQuery code inline before loading jQuery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744018454a2519356.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论