google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






The best way to load external JavaScript In order to load the content of an external JavaScript file, of course we have a lot of ways, but do you know which way is the best? If you say 'No', let read this article, authors will indicate the causes and which way is the best solution for this problem.


Label: best way, best, load, external, solution

Free iPage Web Hosting for First Year NOW



If you're still looking for a reliable web host provider with affordable rates, why you don't take a little of time to try iPage, only with $1.89/month, included $500+ Free Extra Credits for the payment of 24 months ($45)?

Over 1,000,000+ existisng customers can not be wrong, definitely you're not, too! More important, when you register the web hosting at iPage through our link, we're going to be happy for resending a full refund to you. That's awesome! You should try iPage web hosting for FREE now! And contact us for anything you need to know about iPage.
Try iPage for FREE First Year NOW

Not too long ago, I wrote about loading JavaScript without blocking by creating a dynamic <script> tag. When <script> tags are in the flow of an HTML document, the browser must stop rendering and wait for the script file to download and execute before continuing (example). Creating a new <script> tag via JavaScript avoids this issue because it's out of the flow of the document, so the script file is downloaded and executed without waiting. The result: dynamically loading JavaScript files allows your page to render faster and therefore improve perceived performance.

The best technique

Steve Souders has explored several different ways to load JavaScript without blocking both on his blog and in his books. After thinking about it and experimenting, I've come to the conclusion that there's just one best practice for loading JavaScript without blocking:

  1. Create two JavaScript files. The first contains just the code necessary to load JavaScript dynamically, the second contains everything else that's necessary for the initial level of interactivity on the page.
  2. Include the first JavaScript file with a <script> tag at the bottom of the page, just inside the </body>.
  3. Create a second <script> tag that calls the function to load the second JavaScript file and contains any additional initialization code.

That's it! There's really no need to do anything else. The key takeaway is to have only two JavaScript and make the first one as small as possible. For example, the first file may just contain this function:

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

That's a tiny amount of code to get your bootstrapped so it will load incredibly fast (especially when gzipped).

The actual code on your page ends up looking like this:

<script type="text/javascript" src="http://your.cdn.com/first.js"></script>
<script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
    //initialization code
});
</script>

The key to this whole technique is to have just two JavaScript files, so the second one contains everything that's needed to initialize the page. What if your page requires more than two files? Then you should be concatenating your files together either at build time (using something like Sprockets) or at run time (using something like mod_concat or a combo handler). There should never be a time when your page requires more than these two JavaScript files to properly initialize. Each additional HTTP request has overhead, and then you'll need to worry about sequencing the downloads so code is executed in the correct order. By having just two files, you eliminate a large point of concern over which file is downloaded and executed first as well as eliminating unnecessary HTTP requests.

YUI 3 has you covered

YUI 3 is designed around this very premise. You can start by just loading the yui.js file and then use the built-in Loader component to dynamically load the rest of the YUI library. For example:

<script src="http://yui.yahooapis.com/3.0.0b1/build/yui/yui-min.js" type="text/javascript"></script>
<script type="text/javascript">
YUI().use("node", function(Y){
    //initialization code
});
</script>

This code loads in the YUI "seed" file first, then creates a new instance of the YUI object and indicates that the "node" component is necessary. Behind the scenes, YUI constructs a URL with all of the dependencies for "node", dynamically loads it, then calls the callback function when complete. The cool thing about the YUI 3 approach is that you don't need to worry about including the URL for the JavaScript statically, just indicate which components you need and the library figures out the correct URL to download (details).

Conclusion

Though there's been a lot of research on ways to load JavaScript without blocking, there really is just one way that I'd recommend as a best practice. There should really be no need to load anything more than two scripts to get your site initialize and interactive. Make the initial JavaScript file as small as possible and then load in the larger one dynamically to avoid blocking. This is the simplest, easiest way to get all of your JavaScript onto the page without affecting the user experience.

Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of Yahoo!, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.

AIVideo-App.com
Generate your business videos by AI with voice or just text

chatGPTaz.com
Talk to ChatGPT by your mother language

AppAIVideo
Your first FREE AI Video App

Deepfake Video
Deepfake AI Video Maker

Deepfake
Deepfake AI Video Maker

AI Deep Fake
Deepfake AI Video Maker

AIvidio
AI Video Mobile Solutions

AIvideos
AI Video Platform & Solutions

AIvedio
AI Video App Maker

Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE

Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE

Temu Free $500 for New Users
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Free TikTok Ads Credit
Master TikTok Ads for Your Business Marketing

Dall-E-OpenAI.com
Generate creative images automatically with AI

chatGPT4.win
Talk to ChatGPT by your mother language

First AI Product from Elon Musk - Grok/UN.com
Speak to Grok AI Chatbot with Your Language

Tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

iPhoneKer.com
Save up to 630$ when buy new iPhone 16

Buy Tesla Optimus Robot
Order Your Tesla Bot: Optimus Gen 2 Robot Today for less than $20k

JavaScript by day


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web