JavaScript : Can anyone give an example when callback in callback (Pyramid of Doom) is needed?

78 Views Asked by At

The below code does callback inside a callback. Why this is needed? Why can't it be 3 separate calls? Note loadScript just going to create a style tag and add script passed to the src attribute dynamically.

loadScript('/my/script.js', function(script) {

    loadScript('/my/script2.js', function(script) {

        loadScript('/my/script3.js', function(script) {

            // ...continue after all scripts are loaded
        });
    })

});
1

There are 1 best solutions below

0
davidgamero On

In this case, you are using callbacks to ensure that each script completes loading before the next one. They are chained so that all three scripts have to be loaded before continuing the code. The reason this is important is that scripts block the rest of rendering/execution while they load. You can also use async/promise syntax to hold the loading in each line if you want to pretty this up:

const loader = new Loader({
    src: 'cdn.segment.com/analytics.js',
    global: 'Segment',
})

// scriptToLoad will now be a reference to window.Segment
const scriptToLoad = await loader.load()

// https://timber.io/snippets/asynchronously-load-a-script-in-the-browser-with-javascript/

https://www.html5rocks.com/en/tutorials/speed/script-loading/

https://www.sitepoint.com/non-blocking-async-defer/