2

Why does the unobtrusive JavaScript technique require the use of an onload function? Would my unobtrusive JavaScript code work outside of an onload function?

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Joel
  • 4,503
  • 1
  • 27
  • 41
  • The answer is: yes it would. – Felix Kling Aug 15 '14 at 16:15
  • Unobtrusive JavaScript promotes the Separation of Functionality, which you should separate your code from HTML, therefore an onload function should be used to avoid inline script tags. Your "unobtrusive" code would still work outside but it's not unobtrusive anymore. – Derek 朕會功夫 Aug 15 '14 at 16:22

2 Answers2

3

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.

user3568303
  • 102
  • 4
2

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.

Matt S
  • 14,976
  • 6
  • 57
  • 76