简体   繁体   English

使用document.write时脚本执行的顺序

[英]Order of script execution when using document.write

I need to run a library called Fastclick in order to handle the 300ms click delay that's on mobiles. 我需要运行一个名为Fastclick的库,以处理手机上300毫秒的点击延迟。 At the same time, I don't need to run it if I'm not running on mobiles. 同时,如果我不在手机上运行,​​则无需运行它。 So I'm looking to do something like this: 所以我想做这样的事情:

<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>

As you can see, the second script checks to see if FastClick is loaded. 如您所见,第二个脚本检查是否已加载FastClick On my local machine, this works. 在我的本地计算机上,这可行。 However, I'm wondering if it works just because the file is loaded almost instantaneously from the file system (ie no delay) or if in fact, the document.write statement triggers the load and the script execution is on hold until that script is loaded. 但是,我想知道它是否仅由于文件是从文件系统中立即加载(即没有延迟)而起作用的,或者实际上是document.write语句触发了加载并且脚本执行一直保持到该脚本被执行已加载。 I'm looking for the latter behavior: do scripts that are loaded via document.write pause the JavaScript parsing until they're loaded? 我正在寻找后一种行为:通过document.write加载的脚本会暂停JavaScript解析直到加载吗?

Why don't you include the file always and call the function only when you need it? 为什么不总是包含文件并仅在需要时才调用函数? Then you don't have to think about any possibility your way involves: 然后,您不必考虑您的方式涉及的任何可能性:

<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>

When a non-mobile browser has loaded the file one time, it's in the cache and doesn't slow down page load. 非移动浏览器一次加载文件后,它就位于缓存中,并且不会减慢页面加载速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM