Search code examples
javascriptsquarespacemit-scratch

javascript scratchblocks squarespace


I would like to use Scratchblocks (a tool for rendering visual Scratch code blocks from a text listing, on GitHub) on my Squarespace website. The problem I am getting is that the scratchblocks are never rendered on the first load - but only after a refresh.

This is in the header (set in the header for that particular blog):

<script src="https://scratchblocks.github.io/js/scratchblocks-v3.1-min.js""></script>

Then I think I need to call this function at the end of the page - I've put it in the footer:

scratchblocks.renderMatching('pre.blocks');

NOTE: When I view the source I sort of see this JavaScript twice at the end of the page. Not sure what is happening there.

Here's an example of it on my website, where it renders the scratchblocks only after a refresh. [UPDATE - following the fix provided below, this now renders first time, every time as far as I can tell.] [http://www.glennbroadway.com/coding-zone/2017/4/6/simple-collisions-in-scratch]2

Here's an example of someone else using it and it working properly. I've inspected the source and I can't work out how they are doing it. https://codeclubprojects.org/en-GB/scratch/memory/

I've also tried all the different methods listed elsewhere on stackoverflow for getting javascript to load only after the HTML has finished. I can't get any of them to work - but I think the problem is something to do with Squarespace, I just don't have the knowledge to work out what.

Any help would be greatly appreciated.


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/a/42604055/5338581 including:

    window.addEventListener("mercury:load", function(){
       // do stuff
    });
    

    In addition, I would generally recommend placing custom code in the "Footer" code injection area unless you have a specific reason to do otherwise.