开发者

Store JSON inside HTMl

I have a jQuery script that runs on document ready and tries to get some values for configuration. I want to store this values inside JSON.

I've done this:

<div id="settings" style="display: none">{"name": "value"}</div>

However, this is not search engine friendly.

Is there another way to embed JSON inside html 开发者_运维百科and then pulling with jQuery?

Thanks.


You need to keep your data separate from the DOM.

Assuming that you are rendering the page(s) out from some templating system, you're going to have the same data available in the template to render the html version (which search engines read) and the data portion, which your script uses.

Its best not to pollute the namespace of the js thread running in the context of the current page. To that end, I recommend including the data in a script tag assigned to a variable that your lightbox reads after it loads.

For example:

<div> {name} </div>
<div> {value} </div>

<script>
    var mydata = mydata || {};
    mydata.lightbox = {
        "name": "value"
    }
</script>

Alternatively, if you do a xhr or jsonp request to get the json data, you can still use the mydata approach, or just work with the data directly in your lightbox.


Yes, you can create a <script> element with a custom type attribute and an ID. You can use the ID to get that element and retrieve the text content.

Of course, you could just insert the JSON in with your other script, and assign it to a variable.

However, there's no guarantee that search engines will index the contents of a script element.

Instead you could just create a hidden element of some kind, with the JSON as its text content.


Why not output the data in the markup in a search engine friendly way (I guess that's important since you mention it) and access them with ordinary jquery selectors? If you need to, you could hide the data elements with CSS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜