I have a gallery page in my blog directory, hosted by Plesk. Built from vite + react
boilerplate, it’s a very simple SPA.
Before this, my gallery page works like this:
It’s a SPA, so runtime files need to load and initiate first. When page document was downloaded and parsed, the browser started loading <link>
files and after our needed JavaScript files were downloaded and executed.
I have the data fetching logic like this:
1 | const [list, setList] = useState([]); |
This process could take a lot of time (due to the very limited resources the CMS service can use).
Besides, I want to make minimum adjustments to make it faster.
To address this issue and improve the performance of the gallery page, I made the following adjustments:
1 | const generateJSON = async () => { |
<script>
tag in the HTML head, making the data easily accessible as a global variable on the window
object.1 | <head> |
1 | const [list, setList] = useState(window.photos || []); |
By implementing these adjustments, the need for the getData
function and useEffect
hook was eliminated, resulting in a noticeable improvement in the page loading speed. Additionally, the gallery page can now be hosted by a static files server (like NGINX) without requiring an extra runtime environment (like Node.js).
JSONP, or JSON-P (JSON with Padding), is a historical JavaScript technique for requesting data by loading a <script> element, which is an element intended to load ordinary JavaScript.
To use JSON-P, we need to wrap our data into a callback function, and declare our callback function before loading the data file.
1 | <script> |
1 | fetchDataCallback([ |
It’s no better than just putting the data into a global variable in this case.
Follow the guide from next.js, then we still need a Node.js environment to run next.js service.
We can also use next.js to do SSG (Static Site Generation). Use getStaticProps
to insert data into a page template.
We need to rebuild static files when data updates.
To use SSR or SSG both require some extra modifications on the gallery project, so they are not my first consideration. But in different cases, SSR/SSG might be a good option.
It’s important to note that the approach of using a global variable to store the data may expose the data file and could potentially lead to a security risk.
The adjustments made to optimize the gallery page have significantly improved its performance, and while the alternative approaches seems not so good for me, the current solution works great.