0

I decided to design my new job that I use Ajax and i use this cod for load page

html

<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="jquery.js"></script>
<script src="script.js"></script>
</head>

<body>
<div class="menu">
  <ul>
    <li class="page2" id="page2">PAGE TOW</li>
    <li class="page3" id="page3">PAGE THREE</li>
  </ul>
</div>
<div class="load"></div>
</body>
</html>

js

$(document).on('click','.menu li',function(){
    var $this = $(this);
    if($(this).hasClass("page2")) {
      $(".load").load('page2.php');
    }
    else if($(this).hasClass("page3")) {
      $(".load").load('page3.php');
    }
});

This works properly ! But many times when I click on tabs Browser hangs... My question is whether I badly written code? Or this is normal in Ajax If there is a way to help or not use of Ajax

Toprex
  • 155
  • 1
  • 9

1 Answers1

0

The code is not written poorly, but you have chosen an inefficient method of solving this. By attaching your click event to $(document) you are causing a lot of unnecessary overhead and using a lot of resources the browser could be using elsewhere.

Instead, you should try to add the event handler to the closest parent element. Like so...
$('.menu li').on('click', function(e) { //Run your code in here });
See the accepted answer on this stackoverflow question for more information on why this is a better practice.

This answer here has a lot of good information on the subject as well.

Community
  • 1
  • 1
SidTheBeard
  • 379
  • 3
  • 11