【问题标题】:Order of script execution when using document.write使用 document.write 时的脚本执行顺序
【发布时间】:2015-06-02 17:53:01
【问题描述】:

我需要运行一个名为 Fastclick 的库来处理手机上 300 毫秒的点击延迟。同时,如果我不在手机上运行,​​我不需要运行它。所以我想做这样的事情:

<head>
        <script>
        var UserAgent = navigator.userAgent;
        if (screen.width < 851 || UserAgent.indexOf('iPad') !== -1 || UserAgent.indexOf('iPhone') || UserAgent.indexOf('Android')) {
        document.write('<script src=\"/ExternalFiles/Fastclick.js\"></script>');
        }
        </script>

        //second script
        <script>
        if (FastClick) {...}
        </script>
</head>

如您所见,第二个脚本检查是否已加载 FastClick。在我的本地机器上,这有效。但是,我想知道它是否只是因为文件几乎是从文件系统加载的瞬间(即没有延迟),或者事实上,document.write 语句触发了加载并且脚本执行被暂停,直到该脚本加载。我正在寻找后一种行为:通过document.write 加载的脚本是否会暂停 JavaScript 解析直到它们被加载?

【问题讨论】:

    标签: javascript fastclick.js


    【解决方案1】:

    为什么不总是包含该文件并仅在需要时调用该函数?那么您就不必考虑您的方式涉及的任何可能性:

    <head>
            <script src="/ExternalFiles/Fastclick.js"></script>
            <script>
            var UserAgent = navigator.userAgent;
            if (screen.width < 851 || UserAgent.indexOf('iPad') !== -1 || UserAgent.indexOf('iPhone') || UserAgent.indexOf('Android')) {
                    FastClick(...)
            }
            </script>
    </head>
    

    当非移动浏览器一次加载文件时,它会在缓存中,不会减慢页面加载速度。

    【讨论】:

      猜你喜欢
      • 2010-09-10
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 2019-04-16
      相关资源
      最近更新 更多