如何将 JSON-LD 从内联移动到文件内?

How to move JSON-LD from in-line to in-a-file?

我有一份 HTML 文档 JSON-LD 发布如下:

<script type="application/ld+json">
    {
           "@context": {
               "gs1": "http://vocab.gs1.org/v1#",
               "xsd":"http://www.w3.org/2001/XMLSchema#"
           },
           "@id": "retailer:12345",
           "@type": "gs1:Offering",
           "gtin13":"5011476100111",
           "gs1:hasPrice": {
               "gs1:price": "2.49",
               "gs1:priceTypeCode": "USD",
               "@type":"gs1:Price"
           }
      }
</script>

这按预期工作(意味着使用 Google Structured Data Testing ToolStructured Data Linter 它有效且可见)

Using Same Origin (not Cross Origin),如何将行内的JSON-LD移动到文件中?

此方法失败:

<script type="application/ld+json" src="_URL_.json"></script>

这种方法也失败了:

<script type="application/ld+json">
        $(document).ready(function(){
            $.ajax({
                url: "_URL_.json",
                dataType: 'json',
                });        
        });
</script>

如何更正我的方法来创建解决方案,其中 JSON-LD 在我服务器上的文件中,而不是在 HTML 中?

接下来,假设我的站点启用了 CORS。

如何将JSON-LD结构发布为JSONP格式,以便其他域可以订阅JSON-LD数据?

Google Structured Data Testing Tool or the Structured Data Linter 等工具不支持外部引用。可能您的 JSON-LD 的许多消费者也不是。

如果您无论如何都想这样做,则必须使用 , because for the use as data blockscript 元素可能没有 src 属性。

动态包含 JSON-LD 的变体可能适用于为此目的支持 JavaScript 的消费者。 (;可能只是他们的测试工具不能用吧。)

您可以动态生成脚本标签:

<script>
  // do some ajax, get the JSON-LD as `data` and then...
  $.ajax(...).done(function(data) {
    var el = document.createElement('script');
    el.type = 'application/ld+json';
    el.text = JSON.stringify(data);
    document.querySelector('body').appendChild(el);
  });
</script>