After adding an embedded Gist in my WP post, all I see when fetching it through REST API is the embed code, meaning <script src="https://gist.github.com/username/b5f6f2d0xxxxxxxdf9c90cbede0e.js"></script>.
There are solutions to properly render an embedded Gist in WordPress but these solutions work on a WordPress site, not on a non-WP site merely fetching posts from WP.
Any idea how to solve this issue?
EDIT:
As per this suggestion, I tried to extract the script tag from the post and re-inject it into the DOM. But, it still doesn't work. Actually even when simply loading my Gist script into a variable then injecting the content into the DOM, it doesn't work. Yet it works with any other script, for example this:
const tag = document.createElement('script');
tag.src = 'https://my-site.com/test.js';
document.querySelector('body').prepend(tag);
But the exact same snippet using instead my Gist URL fails to execute.
Why don't Gist scripts execute when injected into the DOM?
-
Can you provide more details? What non-WP site are you building? Are you using WP has headless CMS? If yes, what frontend technology are you using?Meera Datey– Meera Datey2021年01月02日 20:58:03 +00:00Commented Jan 2, 2021 at 20:58
-
Does this help you out?J. M. Arnold– J. M. Arnold2021年01月07日 22:33:42 +00:00Commented Jan 7, 2021 at 22:33
2 Answers 2
I believe this is because GitHub uses document.write to insert embedded widgets. However document.write should not be used after a webpage is fully loaded.
// https://gist.github.com/nat/5fdbb7f945d121f197fb074578e53948.js
document.write('<link rel="stylesheet" ...')
GitHub also provides jsonp (json + callback) api to fetch gists. Widgets can be built manually using information in the callback.
// https://gist.github.com/nat/5fdbb7f945d121f197fb074578e53948.json?callback=callback001
/**/callback001({"description":"","public":true...
There are already some projects to do these stuff: https://github.com/mstapp/ajax-gist (jquery.ajax-gist.js)
Comments
A script is rendered after a page loads, so when you make the rest request in your browser, you're just receiving a JSON response containing the post information. The script isn't executed, since the page hasn't been loaded.
For example, take look at this article. In the example, when he retrieves a post, you get a json response like the one below
The solution for you would be to parse the response, and extract the script tags. Then select the script tag containing the GitHub gist.
Once you have the tag, you can embed it in your non-wp site simply be embedding the tag.
4 Comments
<script>...</script>" without actually being executed?Explore related questions
See similar questions with these tags.