Search code examples
javascriptjqueryajaxsquarespace

How to rewrite javascript to force it to load despite Ajax?


I have the following javascript code, the problem is that the Squarespace site i'm working on requires Ajax-loading. Therefore, this code only works if you refresh the page once loaded. More on this issue here https://forum.squarespace.com/topic/87058-why-doesnt-my-javascript-code-work-until-i-refresh-the-page/

I'd be grateful for any pointers on how to rewrite this so that it loads despite the Ajax. It works wonderfully when I disable Ajax but unfortunately I need for that to be turned on for the rest of the site to look good.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script> $(document).ready(function(){
$('.markdown-block .sqs-block-content h3').css('cursor','pointer');
$(".markdown-block .sqs-block-content h3").nextUntil("h3").slideToggle();
$(".markdown-block .sqs-block-content h3").click(function()
{$(this).nextUntil("h3").slideToggle();}); }); </script>


Solution

  • This is a common issue, and there are several common ways that developers approach the solution.

    In your case, inserted via sitewide code injection:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    window.Squarespace.onInitialize(Y, function() {
      $('.markdown-block .sqs-block-content h3').css('cursor','pointer');
      $(".markdown-block .sqs-block-content h3").nextUntil("h3").slideToggle();
      $(".markdown-block .sqs-block-content h3").click(function() {
        $(this).nextUntil("h3").slideToggle();
      });
    });
    </script>