简体   繁体   中英

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. 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. 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. I'm looking for the latter behavior: do scripts that are loaded via document.write pause the JavaScript parsing until they're loaded?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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