Promises - Loading Multiple Files

Video

JavaScript Notes

HTML
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Promise all() with CSS Links</title>
        <meta name="viewport" content="width=device-width">
        <style>
            *{
                font-family: sans-serif;
                background-color: darkmagenta;
            }
        </style>
        <!--
        <link rel="stylesheet" type="text/css" href="big-font.css"/>
        <link rel="stylesheet" type="text/css" href="color-font.css"/>
        -->
    </head>
    <body>
        <h1>Heading</h1>
        
        <script>
            let log = console.log;
            let warn = console.warn;
            const URL1 = "./big-font.css";
            const URL2 = "./color-font.css";
            
            let p1 = new Promise((resolve, reject)=>{
                let link = document.createElement('link');
                link.setAttribute('rel', 'stylesheet');
                link.setAttribute('type', 'text/css');
    
                link.addEventListener('load', function(ev){        // only runs when css properly loads to page
                    //the CSS has been loaded into the style tag
                    log('your css be here')
                    resolve(link);
                });
                link.addEventListener('error', function(err){
                    //there was an error
                    warn('your css is ready, NOT.')
                    reject(err);
                });
                link.href = URL1;
                document.head.appendChild(link);
            });
            
            let p2 = new Promise((resolve, reject)=>{
                let link = document.createElement('link');
                link.setAttribute('rel', 'stylesheet');
                link.setAttribute('type', 'text/css');
    
                link.addEventListener('load', function(ev){        // only runs when css properly loads to page
                    //the CSS has been loaded into the style tag
                    log('your css be here')
                    resolve(link);
                });
                link.addEventListener('error', function(err){
                    //there was an error
                    warn('your css is ready, NOT.')
                    reject(err);
                });
                link.href = URL2;
                document.head.appendChild(link);
            });
            
            Promise.all([p1, p2])
            .then((things)=>{
                log('BOTH the links for CSS have been loaded');
                //now my page can run and use both the scripts
                //OR images, or scripts...
            })
            .catch((err)=>{
                warn('SOMETHING BAD HAPPENED')
            })
            
        </script>
    </body>
    </html>