简体   繁体   中英

jQuery click action before other component load

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.

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>

 <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM