Simple example

NOTE: If you open this page locally keep in mind that this demo works correctly only when it is opened on a proper domain like localhost. If you try to open it from file system (file:///D:/...) Performance Timing API don't take local resources into account (probably because of broken CORS)

Lets assume we have some an endpoint which returns some html markup from the server which should be inserted to the page. As long as our JS and CSS are always loaded during the first page rendering we are fine. It doesn't matter what is sent by the server because we already have all possible styles and scripts loaded on the page. But what if we want to load only those styles and scripts which are needed for a particular page? We can determine those files on the server based on what components are presented on the current page. In case of a full page reload we render them as a <link> and <script> tags. To do so with async requests we should be able to load js and css resources which the returning markup depends on.

Lets mock up our endpoint that returns html markup. In addition to that server must somehow declare dependencies which should be loaded before html appears within the page. It can be done by specifying files names within the response, for example response can look like this:

{
    "html": "<div>...</div>",
    "resources": [
        "/dist/component1.js",
        "/dist/component1.css",
        "/dist/component2.js"
    ]
}

Also we can use headers for specifying resources. By doing this we can keep the original format of the response. Header might look like this:

X-Resources: /dist/component1.js, /dist/component1.css, /dist/component2.js

Our backend uses the second option:

Now we should configure our api and add resource loading logic to it. We will use axios as an HTTP client. We intercept response, loading resources with resourceLoader.load and return html as a result.

Lets create a simple js component that loads html and initializes other components which are declared within markup with data attributes. Despite the example is quite simple, the same logic works in more complicated cases like showing some pages in popups or navigating between pages using an SPA-like approach.

Open Chrome Dev Tools Network Tab and click on «Load content». Bacause demo/base.css is already rendered it won't be downloaded. Unlike it demo/counter.js and demo/counter.css will be downloaded.