博客文章中的Gatsby-js客户端javascript内联 [英] Gatsby-js client side javascript inline in blog post

查看:48
本文介绍了博客文章中的Gatsby-js客户端javascript内联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Gatsby-JS设置博客.我在markdown中有一些包含嵌入式javascript的帖子.

I am trying to setup a Blog using Gatsby-JS. I have some posts in markdown that contain inline javascript.

例如:

<script>window.alert("hello");</script>

我使用"Gatsby serve"命令测试该站点

I test the site using the command "Gatsby serve"

当我通过博客索引浏览到我的帖子时.该脚本未执行.在Web控制台中没有错误.

When I browse to my post via the index of the blog. The script is not executed. In the web console there are no errors.

在帖子页面本身上时.如果我执行F5或ctrl-f5,则会显示你好"警报.

When on the post page itself. If I do F5 or ctrl-f5 then the "hello" alert is displayed.

将网站上传到github页面后,此行为发生了变化.我无法通过F5或通过索引导航来执行脚本.只有当我按ctrl + F5时,脚本才会执行.

After uploading the site to github pages this behavior changes. I cannot get the script to execute by F5 or by navigating via the index. Only when I press ctrl+F5 the script is executed.

live test-blog(它显示多个警报并尝试以图形方式加载). https://dwjbosman.github.io/lstm-neural-network -for-sequence-learning/

live test-blog can be found here (it show multiple alerts and tries to load plotly). https://dwjbosman.github.io/lstm-neural-network-for-sequence-learning/

推荐答案

Dinne的解决方案对我有用.好东西! :)

Dinne's solution worked for me. Nice one! :)

尽管我确实需要避免使用JQuery,所以我在这里发布了一个不依赖JQuery的版本:

I did need to avoid the use of JQuery though so I have posted here a version that doesn't rely on it:

componentDidMount() {

  // Allow in-line JS scripts to be run
  let scripts = document.querySelectorAll('[data-inline-script="data-inline-script"]');
  scripts.forEach(function forEachScript(element) {
    const script = element.innerHTML;
    window.eval(script);
});

这将与以下HTML一起使用:

This will work with the following HTML:

<script data-inline-script="data-inline-script">
    console.log("this works");
</script>

我在一个非常基本的静态站点上使用它.我不确定我到底喜欢使用eval()多少,但是在我的用例中不会造成任何伤害.

I am using this on a very basic static site. I'm not sure how much I like using eval() to be honest but it should cause no harm in my use-case.

更新 尽管上述方法确实有效,但我还需要使用< script src ="...">这不起作用:(这也感觉很hacky.

Update Although the above does work, I also need to include scripts using <script src="..."> which doesn't work :( This feels quite hacky too.

这篇关于博客文章中的Gatsby-js客户端javascript内联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆