spender
spender

Reputation: 120400

Load timeout for Javascript

Consider the following document

<html>
    <body>
        This is some content
        <script type="text/javascript" src="verySlowToRespond.js"></script>
        This is some more content
    </body>
</html>

I'd like first to check my assumption that it is unsafe for the browser to parse beyond the script tag until the script has loaded and executed.

This means that (if my assumption is correct), say verySlowToRespond.js takes 20 seconds to respond, the page DOM cannot be fully assembled until this dependency is resolved.

Supposing verySlowToRespond.js hung about indefinitely? At what point would the browser give up and continue with the parse?

Upvotes: 6

Views: 5210

Answers (3)

Dan
Dan

Reputation: 11069

You are correct. The browser will not render the rest of the page until that script has finished. The timeout would be dependent on the underlying socket properties I suppose.

If you are concerned about the loading time of a script, it is important that the script not make any DOM changes that need to be executed before the rest of the page renders. Then you can add an onload handler to call setTimeout to execute code to load the script asynchronously.

Upvotes: 1

Pointy
Pointy

Reputation: 413712

Correct: the browser won't continue beyond the script tag until it's read and evaluated it.

The browser gives up based on the same timeout rules it uses for pages. It depends on the browser, and on the exact nature of the timeout.

I'm wondering why there'd be such a thing as a slow-to-respond script. Is there something wrong with your hosting? Is the script slow to respond, or does it load and then take a really long time to run?

Upvotes: 3

Kenan Banks
Kenan Banks

Reputation: 211942

Yes your first assumption is correct. Browsers stop rendering until <script> tags finishing loading AND executing.

The behavior on very long running scrips is browser-dependant. Newer browsers will often give you a chance to abort the script. Older browsers may need to be force-closed.

Upvotes: 2

Related Questions