Prevent JSON-Pretty from being cached for JavaScript files that rely on it

I recently created a Squarespace website using a template that features a unique masonry type gallery layout, which can be viewed at the following link: . Although I was drawn to this template specifically for its gallery design, I've encountered several limitations with the overall template, prompting me to essentially rebuild the site from scratch. As I am not in developer mode, my ability to modify the code is limited to adding code in the header, on individual pages (excluding the gallery), and sitewide in the footer using a code block. My primary objective is to find a solution that addresses these issues by adding code solely in the header.

The main drawback I've encountered involves the gallery functionality. By default, clicking on a thumbnail opens a lightbox rather than redirecting to a specific hyperlink. While Squarespace allows for the assignment of "Clickthrough URL" attributes via the editing panels, these are disregarded, resulting in the lightbox action. For my website, it is essential that clicking on a thumbnail directs users to the corresponding projects page instead. To address this issue, I found a script shared by another Squarespace user, nicknamed ghostcat, which is included in the header:

<script>
  var currentPageBaseURL=window.location.href.split("?")[0];
   Y.on("domready",function(e){
   Y.io(currentPageBaseURL+"?page=1&format=json-pretty", {
     on:{success: jsonLoaded}
  });
  function jsonLoaded(err,data){
  try{
   var jsonResponse = Y.JSON.parse(data.responseText);
   var items=jsonResponse.items
   Y.all("#thumbList .thumb, #galleryWrapper .slide").each(function(e){
     var thumbId=this.getAttribute("data-slide-id");
     for(var i=0;i<items.length;i++){
       if(thumbId==items[i].id && items[i].clickthroughUrl){
         this.setAttribute("data-clickthrough-url",items[i].clickthroughUrl).on("click",function(e){
           e.preventDefault();
           e.stopPropagation();
          window.open(this.getAttribute("data-clickthrough-url"),'_self');
         })
       }
     }
   })
   }catch(e){}
   }
   });
</script>

Although this script effectively fulfills the desired functionality, it has one major drawback - returning visitors to the site must clear their cache for the updated thumbnail links to work correctly. If a visitor had previously accessed the project page and new thumbnails were added since then, only the existing thumbnails will function properly, while the new ones will trigger the lightbox action.

I've attempted incorporating the code in the footer without success, as well as uploading the script as a .js file and calling it on page load. Even after editing the filename and updating the gallery, the issue persisted. Surprisingly, the script does not appear to be cached by Chrome or Safari, yet clearing the cache prior to visiting the page consistently resolves the problem.

Currently, I have implemented a redirect strategy where I append the gallery's URL with the date (e.g., www.website.com/work -> www.website.com/work-041718) and establish a 301 redirect. While this solution works, it feels cumbersome to modify the URL with the date for each gallery iteration.

Are there any modifications I can make to the script or alternative tactics I can employ to overcome this challenge?

I am open to further clarification and suggestions to address this issue.

EDIT - Upon reviewing the inspector, I noticed that an XHR file is being cached. This file contains all the image attributes set in the panel, including the Clickthrough URL, and can be found at www.website.com/gallery-page?page=1&format=json-pretty. This discovery leads me to believe that this XHR URL may be at the root of the problem, as the script functions based on the data retrieved from this source. Could this insight potentially aid in finding a solution?

Answer №1

There could be a potential explanation (assuming your code is in a .js file rather than a script tag in the markup). If a user has previously downloaded this file and their cache is enabled, the browser will retrieve the saved file instead of the one from the server. The file will still be part of the request, but checking the network inspector could show whether it is being served from a cached source - usually resulting in a much faster response time (a few milliseconds compared to a few hundred).

Many production sites address this issue by hashing the file or utilizing a version tag as a solution.

Another option is to include your javascript code directly in the DOM using a script tag, although this may introduce other potential problems. This method works because the HTML file is served directly from the server to the client, which is typically not cached (although it could be). If your code is within a script tag in the markup, it is likely being cached on the server side and may require clearing on the server.

Answer №2

The issue stemmed from the script relying on the JSON-pretty version of the webpage, located at www.website.com/gallery-page?page=1&format=json-pretty. Unfortunately, this version was being cached by the browser, leading the script to reference an outdated list of gallery items and clickthrough URLs.

To resolve this issue, a new script was implemented following the steps outlined here:

var xhr = new XMLHttpRequest();
xhr.open("GET", uriOfCachedPage, true);
xhr.setRequestHeader("Cache-Control", "max-age=0");
xhr.send();

Using uriOfCachedPage = "", effectively prevented caching and resolved the issue in initial testing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating interfaces for applications that are driven by events in JavaScript

When it comes to designing an application, traditional UML Class diagrams may not always be useful, especially for programs that do not heavily rely on classes. For instance, in a JavaScript application that is mainly event-driven, where you listen for eve ...

Getting Started with NodeJS Child Process for Electrons

My current challenge involves integrating a Gulp setup with debugging electron-quick-start. I am attempting to close and reopen Electron when changes are made to my source files using child_process.spawn. Launching the application seems to work fine, but w ...

Issues with jQuery Ajax Request Parsing JSON Data in Internet Explorer

My code is working perfectly with ajax jQuery call to json, except for IE. jQuery.ajax({ url: "/session/json.php", type: "GET", data: "", success: function(data) { var obj = jQuery.parseJSON( ...

Choosing the following choice using the Material-UI Select tool

Looking for a way to enhance my dropdown select from MUI in a Nextjs application by adding two arrows for navigating to the next/previous option. Here's what my code currently looks like: <StyledFormControl> <Select value={cu ...

Should Angular libraries be developed using Typescript or transpiled into JavaScript?

Currently, I am in the process of developing a library that will be available as an Angular module through npm. The library itself has been written using typescript. Everything was functioning perfectly up until Angular version 5.0.0, but after this update ...

javascript regular expression

Is there a way to extract the text that falls between the first colon and the first period in a string? s:4332Hhj4j32hh432kjh.EF4324rf46543DSVC3443 I attempted using the following regex: /:(.*?)\./g Unfortunately, it still captures the colon and p ...

What is the best way to display only the host and pathname of the links generated by Array.map()?

I am currently utilizing Array.map() to display a list of files in cache: <div data-offline></div> <script> var version = 'v1:'; if (navigator && navigator.serviceWorker) { caches.open(versio ...

Concurrent Accordion and Color Transformation Animations

I am currently utilizing jQuery version 2.0.3 and jQuery UI version 1.10.3, specifically using the accordion feature. I am attempting to modify the color of the accordion panels as they open and close by implementing the following code: $(".main-content") ...

retrieving the value of a field within an array

Here is my code snippet: <div class="label">{{ item.data[0] }}</div> and in the view, this is what I have: { "id": 6, "firtname": "JHON ", "lastname": "SCALA", "fullname& ...

A guide to efficiently transferring data from JSON files to MySQL databases with PHP

Having acquired a json file containing multiple table records, I am faced with the task of transferring this data from my local mysql database to an online database that shares the same schema. However, each table does not have an equal number of fields or ...

Issue arises from having multiple instances of CKEditor5 when transferring information to a Modal

Utilizing AJAX requests to fetch data from the database has been helpful, except for one issue: when passing the data into CKEditor5, I encounter an error. Each time I close and reopen the modal, a new instance of the modal is displayed even though the dat ...

Retrieve the name of the file from a given URL by using JavaScript/jQuery, even when only the directory path is

I need to extract the current filename from the URL using: $currentFile = window.location.pathname.split("/").pop(); This method functions properly when the full path looks like: http://www.yoursite.com/folder/index.php It will return index.php, index. ...

Utilizing React to Style Background Positions

I've been struggling to position a block of rendered jsx on the right side of the first block for hours now. Despite trying various options like marginTop, marginLeft, and even backgroundPosition based on my research, I still haven't been success ...

The functionality of Angular.js ajax and apply is experiencing technical difficulties

As I venture into the world of angular.js, I am facing a challenge with displaying the correct content on my website. The pages' content is fetched via AJAX (currently from static data, but eventually from a database). When I place a block with the ng ...

Unable to handle JQuery POST to PHP in success function

I am struggling with a jQuery post function that is supposed to call a PHP script in order to retrieve a value from the database. Although I can see in Firebug that the PHP file is being called and returning a 200 OK status, the success function in my JS ...

Difficulty organizing form inputs into arrays prior to submitting them through AJAX

I am currently developing a complex multi-step form that involves various sections such as Company, Job Site, Contact, and Product. My goal is to efficiently gather the form data either as an array or object before converting it into a string for transmiss ...

Angular JS appears to be causing the DOM to freeze up while utilizing the ng-repeat directive to loop through

I have a current app where clicking a button triggers an $http request to fetch and return some data. The retrieved information is then used to update the $scope variables rows and columns, which are then looped through using ng-repeat. However, I've ...

Unable to access the "target" property while transferring a value from child to parent component

Within my project, the student component is considered a child component of the main app component. Inside the template of the student component, there is an input element defined like so: <input type='text' #inputbox (keyup)='onkeyUp(i ...

Error with REST service and browser history in ReactJS

I am currently developing my first Java application, which is a REST service built with Spring Boot. It utilizes technologies such as WEB, REST, JPA, Thymeleaf, and MySQL. The API is fully functional, but I wanted to enhance it with a user interface. After ...

Having difficulty entering text into a "Search Input Field" that is a react component in testcafe

Struggling to input text in a "Type to search dropdown" that is a react component. While able to click on the component, typing any text seems to be an issue. Listed below is an example of the code: import { Selector } from 'testcafe'; test(&ap ...