Для получения полного доступа
зарегистрируйтесь

How push jquery.js to body end (frontend optimization)


"Golden" rule of frontend optimization often recommends to insert all JS scripts on page end. However usualy we can't remove <script src="//jquery.js"> from page <head>, because page content can contain many onReady-handlers, for example $(function(){ ... }).

This short snippet allows move jquery.js from <head> to end of <body> without changing onReady-handlers.

Snippet:

<head>
	<script>
		// Fallback code for the jQuery inline scripts on pages:
      if (window.jQuery === undefined) {
          window.jQueryReadyHandlers = [];

          window.$ = window.jQuery = function (callback) {
              window.jQueryReadyHandlers.push(callback);
              return window.$;
          };

          window.$.ready = window.$;
      }
  	</script>
    <!-- ...some head items -->
</head>
<body>

	<!-- ...some page content -->
    
    <script> 
    	// some onReady-handlers
      $(function(){
          console.log('First callback');
      });

      jQuery(document).ready(function(){
          console.log('Second callback');
      });
    </script>
    
    <!-- ...some page content -->


	<script src="//js/jquery.min.js"></script>
    <script>
    	jQuery(window).load(function(){
        	if(window.jQueryReadyHandlers) { 
            	$.each(window.jQueryReadyHandlers, function(index,func){  
                	$(func);
                });
            }
        });
    </script>
</body>

Чтобы увидеть комментарии, нужно быть участником сообщества

Регистрация