Skip to Navigation

Yet another reason to avoid inline scripts

Written on June 14th, 2007 by Jesse.

I think it's fairly common knowledge that it's best to include all scripts in the head of an HTML page, but do we really know why? Sure, unobtrusive javascript makes your code cleaner and more manageable. It also separates out the behavior from the structure. But are there any performance benefits?

I was tasked to figure out how to incorporate a 3rd party vendor's product into my company's website(s) recently, and the one thing that jumped out at me was that this product required a very rigid structure. Part of the required markup was an inline javascript tag. Granted, this extra markup didn't fit in well with our templating system, but I felt like I needed more of an argument - to actually figure out if this was the best way for the 3rd party to be implementing its own functionality.

I was wondering how loading external (from another domain) scripts within the document body would affect the page load time. Would it allow the page to render, like how images do? How would it affect page load time? After a quick google, I ended up at the Mozilla Developer Center, only to learn that Inline scripts can be expensive for page loading since the parser must assume that an inline script can modify the page structure.

I wasn't satisfied...but it did make sense. As long as a script within the body of a web page is executing, the rendering of the page must wait, because the structure of the page may actually be changing at that moment. So I wrote a quick test page which calls a sleep() method for 8 seconds. Guess what? Executing a script while the body is still loading prevents the page from rendering - it waits until the script has finished. I haven't tested what would happen if you link to a static javascript file which contains similar code which is automatically run, but I assume it would behave the same way. I would also assume that if you make an asynchronous call, then it will just run it the background and not impact the page rendering, but I haven't had a chance to test that yet.

I think (hope) that it's very unlikely that someone will us an inline script to do some complex and tedious task, but now there's another reason to avoid inline scripts. They can cripple performance.

More Reading

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.