

Here’s a technique you can use to asynchronously load JavaScript files: // Get the first script element on the page


So… if not document.write(), how should you inject scripts via JavaScript? A Better Way

10% more page loads reaching first contentful paint (a visual confirmation for the user that the page is effectively loading), 25% more page loads reaching the fully parsed state, and 10% fewer reloads suggesting a decrease in user frustration.As a result of blocking the load of these scripts, we saw the following improvements on those loads: We saw that 7.6% of all page loads on 2G included at least one cross-site, parser-blocking script that was inserted via document.write() in the top level document. We collected data from a 28 day field trial on 1% of Chrome stable users, restricted to users on 2G connections. Based on instrumentation in Chrome, we've learned that pages featuring third-party scripts inserted via document.write() are typically twice as slow to load than other pages on 2G. But why?įor users on slow connections, such as 2G, external scripts dynamically injected via document.write() can delay the display of main page content for tens of seconds, or cause pages to either fail to load or take so long that the user just gives up. You may have heard that you shouldn’t use document.write() to inject scripts into a page. Lists Unordered Lists Ordered Lists Other Lists HTML Block & Inline HTML Classes HTML Id HTML Iframes HTML JavaScript HTML File Paths HTML Head HTML Layout HTML Responsive HTML Computercode HTML Semantics HTML Style Guide HTML Entities HTML Symbols HTML Emojis HTML Charset HTML URL Encode HTML vs.A better way to load scripts with JavaScript (or, why document.write() sucks)
