Saturday, December 29, 2012

Best practices to reduce memory leak in jQuery/Javascript



1. if you want to remove HTML DOM elements,  follow the below  steps to release memory claimed by DOM elements.

a) $("#content").off();   // unbind all the events of that control.
b) $("#content").empty(); or   $("#content").html("");  // -- Remove the child elements before removing the element itself.
c) $("#content").remove();  // -- remove the element itself.

2. Before removing the element, please follow the above three steps for each child element from lower level to higher level.

3. if you have used any variable to store the values, follow below steps to release memory claimed by variable.

delete x;  // x is variable
x = null;

4. if your plugin has functions or properties, please set it to null.

[object].sortable = null;

Thursday, December 06, 2012

Solution: Replacing jQuery attr onclick event not working in IE (Internet Explorer) Browser


Before IE 9, if you are replacing HTML element onclick attribute using jquery, the event won't fire. See below HTML and jQuery to replace the onclick attribute of anchor tag.

HTML:

   <div>  
     <a id="atest" style="cursor:pointer" onclick="showAlert1();"> Click to fire an event</a>  
   </div>  


jQuery:


  <script type="text/javascript">  
     $(function () {  
       $("#atest").attr("onclick", "showAlert1();showAlert2();");  
     });  
     function showAlert1()  
     {  
       alert("Alert 1");  
     }  
     function showAlert2() {  
       alert("Alert 2");  
     }  
   </script>  

Above jQuery, replacing the onclick attribute to show the two alert instead of single alert. This code won't work in IE 7/8 browser. To fix this, you can bind a custom click event using click method in jQuery.



  <script type="text/javascript">  
     $(function () {  
       $("#atest").click(function () { showAlert1(); showAlert2(); });  
     });  
     function showAlert1()  
     {  
       alert("Alert 1");  
     }  
     function showAlert2() {  
       alert("Alert 2");  
     }  
   </script>  

In some cases, you may have to replace the onclick attribute with your own custom attribute based on some logical situation. In that case,it's not easy to bind click event dynamically. Here is the magic to replace the entire anchor element with custom attribute anchor element.

  <script type="text/javascript">  
     $(function () {  
       var onc = $("#atest").attr("onclick");  
       var elemHTML = $("#atest").parent().html();  
       var finalElement = elemHTML.replace(onc, onc + "showAlert2();");  
       $("#atest").parent().html(finalElement);  
     });  
     function showAlert1()  
     {  
       alert("Alert 1");  
     }  
     function showAlert2() {  
       alert("Alert 2");  
     }  
   </script>