【问题标题】:XML parse blocking page loadXML 解析阻止页面加载
【发布时间】:2013-06-08 06:11:42
【问题描述】:

我正在使用以下脚本来解析 XML 文档并将其显示在网站上,这一切都很好,但是我在我的 html 文档中间内嵌了这个脚本。

它似乎阻止了我的页面加载大约 300 毫秒,所以我想把它放在文档的末尾来解决这个问题。

所以我的问题是......我怎样才能在文档末尾有这个脚本,但仍然在文档中间显示输出。

<script>
if (window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest();
} else {
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "abc.xml", false);
xhttp.send();
xmlDoc = xhttp.responseXML;
x = xmlDoc.getElementsByTagName("xr")[0].attributes;
att = x.getNamedItem("value");
document.write(att.value);
</script>

谢谢!

【问题讨论】:

    标签: xml parsing xmlhttprequest document.write


    【解决方案1】:

    如果您使用的是 jQuery 库,您可以尝试以下方法 (putting the script at the bottom):

    <body>
        <div id="test">Click here to show XML</div>
        <script>
            $(document).ready(function(){
               function showXML(){
                  if (window.XMLHttpRequest) {
                     xhttp = new XMLHttpRequest();
                  } else {
                     xhttp = new ActiveXObject("Microsoft.XMLHTTP");
                  }
                  xhttp.open("GET", "abc.xml", false);
                  xhttp.send();
                  xmlDoc = xhttp.responseXML;
                  x = xmlDoc.getElementsByTagName("xr")[0].attributes;
                  att = x.getNamedItem("value");
                  document.write(att.value);
               }
               $("#test").on('click', function(){
                  showXML();
               });
           });
        </script>
    </body>
    

    【讨论】:

    • 如何在没有点击的情况下使用此方法?理想情况下,我希望它自动加载和显示,但不会阻止页面加载.. 谢谢
    【解决方案2】:

    如果你不介意做一个 onclick 函数...

    <body>
        <div onclick="showXML()">Click here to show XML</div>
        </body>
        <script>
        function showXML(){
        if (window.XMLHttpRequest) {
            xhttp = new XMLHttpRequest();
        } else {
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhttp.open("GET", "abc.xml", false);
        xhttp.send();
        xmlDoc = xhttp.responseXML;
        x = xmlDoc.getElementsByTagName("xr")[0].attributes;
        att = x.getNamedItem("value");
        document.write(att.value);
        }
        </script>
    

    【讨论】:

    • 恐怕它需要加载而不是点击,如果这对 $( document ).ready() 有帮助,我会在网站上使用 jquery,谢谢
    • 等等,你解决了吗?或者你是问如何用 onload 和 $( document ).ready() @user2201059 做到这一点?
    • 不,我还没有解决它,所以如果你能告诉我如何使用该方法(或任何其他 onload 方法),那就太好了! :)
    猜你喜欢
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2011-01-13
    • 2021-11-01
    相关资源
    最近更新 更多