问题
Why does the unobtrusive JavaScript technique require the use of an onload function? Would my unobtrusive JavaScript code work outside of an onload function?
回答1:
Global Javascript outside of any function will execute immediately as it's interpreted. onload
event is used when you want your JS to run only after the DOM is fully evaluated.
Use onload
to work with the DOM and/or to delay execution until the page is shown to the user.
Since the load event is a standard, it's not incompatible with the concept of unobtrusive Javascript.
回答2:
Unobtrusive JavaScript is a best practice methodology for attaching JavaScript to the front-end of a website. It’s an ideal to strive toward and something we should bear in mind whenever we’re adding JavaScript to a site.
It is the separation of behaviour from markup or structure. Just like the CSS gurus of old taught us there should be a separation of layout from markup, there should be a separation of behaviour from markup. That’s HTML for the content and structure of the document, CSS for the layout and style, and Unobtrusive JavaScript for behaviour and interactivity. Simple.
来源:https://stackoverflow.com/questions/25330053/unobtrusive-javascript-onload-function