虽然目前无法使用script标签,但iframe如果它来自同一域,则可以使用。
<iframe
id="mySpecialId"
src="/my/link/to/some.json"
onload="(()=>{if(!window.jsonData){window.jsonData={}}try{window.jsonData[this.id]=JSON.parse(this.contentWindow.document.body.textContent.trim())}catch(e){console.warn(e)}this.remove();})();"
onerror="((err)=>console.warn(err))();"
style="display: none;"
></iframe>
要使用上述内容,只需将idandsrc属性替换为您需要的内容。在id(我们将在这种情况下,假定等于mySpecialId)将被用于存储数据的window.jsonData["mySpecialId"]。
换句话说,对于每个具有id和 使用onload脚本的iframe,都会将该数据同步加载到指定window.jsonData下的对象id中。
我这样做是为了好玩并表明它是“可能的”,但我不建议使用它。
这是使用回调的替代方法。
<script>
    function someCallback(data){
        /** do something with data */
        console.log(data);
    }
    function jsonOnLoad(callback){
        const raw = this.contentWindow.document.body.textContent.trim();
        try {
          const data = JSON.parse(raw);
          /** do something with data */
          callback(data);
        }catch(e){
          console.warn(e.message);
        }
        this.remove();
    }
</script>
<!-- I frame with src pointing to json file on server, onload we apply "this" to have the iframe context, display none as we don't want to show the iframe -->
<iframe src="your/link/to/some.json" onload="jsonOnLoad.apply(this, someCallback)" style="display: none;"></iframe>
在 chrome 中测试,应该在 Firefox 中工作。不确定 IE 或 Safari。