使用react插入脚本标记,脚本不包含javascript代码

时间:2016-11-07 11:48:16

标签: javascript reactjs

我正在使用react Js,我想在我的网站中为SEO目的插入脚本标记。请参考以下代码和成就的可能性:

custom Script

<script type='application/ld+json'> 
    {
        "@context": "http://www.sample.org",
        "@type": "sampleBusiness",
        "name": "test",
        "url": "https://www.example.in",
        "logo": "https://www.example.in/img/logo1.png",
        "image": "https://www.example.in/img/logo1.png",
        "description": "This is for test purpose only and shall not be used elsewhere!",
        "address": {
            "@type": "sampleAddress",
            "streetAddress": "John Doe, #27, common street, developer house",
            "addressLocality": "Test/Development",
            "addressRegion": "TestRegion",
            "postalCode": "testData",
            "addressCountry": "DeveloperContry"
        },
        "email": "hop(at)example.in",
        "telephone": "someexample"

    }
</script>

我尝试添加这样的内容,但它不会起作用:

render : function() {
    return (
        <script>
            {{
        "@context": "http://www.sample.org",
        "@type": "sampleBusiness",
        "name": "test",
        "url": "https://www.example.in",
        "logo": "https://www.example.in/img/logo1.png",
        "image": "https://www.example.in/img/logo1.png",
        "description": "This is for test purpose only and shall not be used elsewhere!",
        "address": {
            "@type": "sampleAddress",
            "streetAddress": "John Doe, #27, common street, developer house",
            "addressLocality": "Test/Development",
            "addressRegion": "TestRegion",
            "postalCode": "testData",
            "addressCountry": "DeveloperContry"
        },
        "email": "hop(at)example.in",
        "telephone": "someexample"

    }}
        </script>
    )   
}

2 个答案:

答案 0 :(得分:0)

在React中包含脚本标记并不常见 - 当反应呈现时,您的脚本不会被执行,因为它会动态地放入dom中。

您可以尝试使用react-helmet库,这可能正在满足您的需求:https://github.com/nfl/react-helmet

可以通过包含头盔和使用代码段来包含它:

 script={[
   {"type": "application/ld+json", "innerHTML": `{ "@context": http://schema.org" }`}
 ]}

答案 1 :(得分:0)

如果您的应用程序是在客户端呈现的,那么将此脚本添加到客户端上的dom,对SEO没有多大帮助。因为搜索引擎抓取工具不会看到它。因此,不要在应用程序中呈现它,而是将其添加到应用程序外的html页面。

我猜你有一个.html文件,如下所示,你的应用程序的root dom元素。像这样包括你的脚本。

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Your app</title>
  </head>
  <body>
    <script>
      // Content of your script here
    </script>
    <div id="root"></div>
    <script src="/static/bundle.js"></script> <>
  </body>
</html>