Home > Back-end >  jQuery click action before other component load
jQuery click action before other component load

Time:08-31

Optimized my website with WP Rocket and delayed javascript execution with some exclusions. Excluded: /jquery-?0-9.(.min|.slim|.slim.min)?.js and js-(before|after) and my script which has code:

jQuery(document).ready(function() {
    console.log('F Loaded');
  jQuery('#div_id').bind('click', function() {
    jQuery('#desired_element').css('display','block');
    console.log('Clicked')
  });
});

When I'm loading a website - getting first message in console "F loaded", but after click - action happens only after all rest scripts are loaded. Is there any way to avoid waiting for all other scripts and make that action (style add after click) immediately ? Tried with plain javascript but got same result.

CodePudding user response:

You can use modern way to write click event outside the document ready you will be able to perform click outside document ready.

$(document).ready(function() {
    console.log('F Loaded');
});
$(document).on('click', '#div_id', function(event){
    jQuery('#desired_element').css('display','block');
    console.log('Clicked')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_id">Click me</div>
<div id="desired_element" style="display:none">TEST CONTENT</div>

CodePudding user response:

<html>
  <head><title>test</title></head>
  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="Clickme">Click me</div>
    <div id="Contentsection" style="display:none">Test Content content....</div>
    <script>
    $('#Clickme').on('click', function(event){
        $('#Contentsection').show();
        console.log('Clicked')
    });
    </script>
  </body>
</html>

  • Related