What is Unobtrusive Javascript in layman terms?

倖福魔咒の 提交于 2019-11-26 06:39:14

问题


What is Unobtrusive Javascript in layman terms? An example would be nice to aid my understanding.


回答1:


Checkout the wikipedia article:

  • Unobtrusive JavaScript

"Unobtrusive JavaScript" is a general approach to the use of JavaScript in web pages. Though the term is not formally defined, its basic principles are generally understood to include:

  • Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support advanced JavaScript functionality[2]

So it is basically separating behavior or javascript from presentation or html.

Example:

<input type="button" id="btn" onclick="alert('Test')" />

That is not unobstrusive javascript because behaviour and presentation are mixed. The onclick shouldn't be there in html and should be part of javascript itself not html.

With above example, you can go unobstrusive like this:

<input type="button" id="btn" />

JavaScript:

var el = document.getElementById('btn');
el.onclick = function(){
  alert('Test');
};

That time we have separated javascript from html with a very basic example.

Note:

There is more to unobstrusive javascript as can be checked out on wikipedia article.



来源:https://stackoverflow.com/questions/4478795/what-is-unobtrusive-javascript-in-layman-terms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!