admin管理员组文章数量:1202361
Assuming one has inline Javascript code in a HTML document (the body for example), is this piece of Javascript always executed before JQuery document-ready code?
For example, is the following safe?
...
<body>
<script type="text/javascript">
var myVar = 2;
</script>
...
</body>
...
$(document).ready(function() {
alert('My Var = ' + myVar);
}
If not, how can I make it safe knowing myVar
is defined in an inline/block code?
Assuming one has inline Javascript code in a HTML document (the body for example), is this piece of Javascript always executed before JQuery document-ready code?
For example, is the following safe?
...
<body>
<script type="text/javascript">
var myVar = 2;
</script>
...
</body>
...
$(document).ready(function() {
alert('My Var = ' + myVar);
}
If not, how can I make it safe knowing myVar
is defined in an inline/block code?
3 Answers
Reset to default 12Yes, the above code is safe. Inline JS is executed as it is encountered while the document is being parsed top to bottom. The document ready handler is executed when the document is ready (obviously), and it won't be ready until the whole document has been parsed including inline scripts.
Note that you don't really need a document ready handler if you include the code that it wraps as the last thing in the document body, because at that point not only will other inline JS have executed but all of the document elements will have been added to the DOM and thus be accessible from JS.
Yes, inline JavaScript is executed while the HTML is parsed.
It's safe to do that, as long as you don't try to get a reference to a DOM element that wasn't parsed yet (i.e., any element after the script block in the HTML soure code). You can also reference any variable defined on earlier script blocks (as long as they are in scope).
And, as Matt Browne pointed out in his comment, it's also generally safe not to use a DOMContentLoaded listener (or the oldIE workaround, or window.onload) if you put your script that relies on the DOM being loaded right before the closing </body>
tag. At that point, all HTML elements will be in the DOM already (unless you have further elements after </body>
, which would be invalid HTML).
It is safe to assume that myVAr
is accessible from within the $(document).ready(function() {})
.
If you run the code in your HTML, myVar
becomes a property of the window
JS global object (i.e. window.myVar
). I don't think it is necessary to create it locally in the jQuery function.
本文标签: jqueryIs inlineblock Javascript executed before documentreadyStack Overflow
版权声明:本文标题:jquery - Is inlineblock Javascript executed before document-ready? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738651183a2104880.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论