Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits and/or pitfalls of calling a function directly from an anchor tag vs creating events onload?

Is there a proper/standard way?

<a href="#" onclick="function();">Link</a>

vs

<script>
$(document).ready(function(){
   $('#link1').click(function(){ ... });
});
</script>
<a href="#" id="link1">Link</a>
like image 726
Ryan Detzel Avatar asked Nov 18 '11 18:11

Ryan Detzel


People also ask

Why do we need to use an onload event in the script?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

Why do we need window onload?

The only reason people used window. onload is because they mistakenly believed scripts needed to go in the head section. Because things are executed in order if your script was in the head section then the body and your content didn't yet exist by definition of execute in order.

What is the difference between document load event and document DOMContentLoaded event?

Differences. The DOMContentLoaded event fires when all the nodes in the page have been constructed in the DOM tree. The load event fires when all resources such as images and sub-frames are loaded completely.

Should I use onload?

The window. onload event gets fired when all resources - including images, external script, CSS - of a page have been loaded. If you want to do something when that event has been fired you should always use the window.


2 Answers

Personally I prefer the second. It allows me to separate my markup and script. This means that scripts could be placed in a separate file and since scripts are static resources they get cached, minified, obfuscated, ... And reduced markup size obviously leads to reduced bandwidth and so faster loading site. In a web page there are really 3 notions that should not be mixed:

  • markup
  • scripting
  • styling
like image 141
Darin Dimitrov Avatar answered Sep 19 '22 09:09

Darin Dimitrov


From the top of my head:

  1. The first one only allows one handler per time on a single element
  2. The first one cannot have access to anything but global scope
  3. The first one doesn't allow for event delegation, because some events need to use event capture in standards compliant browsers for delegation to work (namely blur and focus), and you cannot select whether to use capture or bubble there.
  4. The first one ... read @DarinDimitrov's answer.

You would use the first one when... ask facebook or hotmail. I've got nothing on that.

like image 42
Esailija Avatar answered Sep 19 '22 09:09

Esailija