When writing technical tutorials, providing a way for readers to interact with code snippets can improve the learning experience. Usually, this requires using heavy third-party embeds or setting up a backend to save and execute code.
A simpler approach is to use a stateless editor that handles code injection via URL parameters. This guide explains how to use the SE API to turn static code blocks into editable previews.
Overview of the SE API
The SE API is designed for technical bloggers who want to offer a “Try it Live” feature without the overhead of a database. It works by taking code from your existing page elements, encoding it, and passing it to a browser-based editor.
Because the editor is static and runs entirely in the client’s browser, it is fast and respects user privacy.
Implementation Steps
To set up live previews on your site, follow these steps.
1. Script Integration
First, include the API helper script in your HTML. This script identifies specific links on your page and handles the encoding logic.
<script src="https://editor.siddharth.at/api.js"></script>
2. Organizing Code Blocks
Place the HTML, CSS, or JavaScript you want to share inside elements with unique IDs. Using <pre> tags is recommended to ensure the code structure and indentation are preserved.
<pre id="my-html-code">
<div class="box">Live Preview</div>
</pre>
<pre id="my-css-code">
.box { background: #eee; padding: 20px; }
</pre>
3. Creating the Trigger Link
To create a link that opens the editor, use an anchor tag with the class sideditor. Use the html, css, and js attributes to point to the IDs of the code blocks created in the previous step.
<a href="#" class="sideditor" html="my-html-code" css="my-css-code">
Open in Editor
</a>
Considerations and Limits
Since this method uses the URL to pass data, there are a few technical constraints to keep in mind:
- Character Limits: URLs have length limits. To ensure compatibility across all browsers and hosting providers, try to keep the raw code under 8,000 characters.
- Lines of Code: This setup is ideal for snippets and components (roughly 200–300 lines).
- External Dependencies: If your code requires libraries like Tailwind CSS or a specific font, include the necessary
<link>or<script>tags within your HTML code block. - Mobile Compatibility: The editor is designed to be responsive, making it accessible for readers on mobile devices.
Conclusion
Using a URL-based injection method allows you to add interactivity to your articles with minimal configuration. It provides a functional environment for readers to test and modify code without leaving the context of the tutorial for too long.
For more technical details, you can refer to the API documentation.