Search code examples
javascriptsquarespace

Javascript only loads after refresh (Squarespace)


I have a javascript running on a squarespace site, but it only seems to work after the page has been refreshed once.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script>
    $(document).ready(function(){
    $('.markdown-block .sqs-block-content h2').addClass('ui-closed').css('cursor','pointer');
    $(".markdown-block .sqs-block-content h2").nextUntil("h2").slideToggle();
    $(".markdown-block .sqs-block-content h2").click(function() {
      
      $(this).nextUntil("h2").slideToggle();
      $(this).toggleClass('ui-closed ui-open');
      });
    });
    </script>


Solution

  • In Squarespace, when your custom Javascript only works after a page refresh, it most likely has to do with Squarespace's AJAX loading:

    Occasionally, Ajax may conflict with embedded custom code or anchor links. Ajax can also interfere with site analytics, logging hits on the first page only.

    You may be able to disable AJAX for your template. Or, see the other approaches outlined here: https://stackoverflow.com/questions/54493314#54493314