How to load a library only once, or how to check if a library has been loaded? I am making an asynchronous single page application in Drupal 8. So far everything is working nicely. However, it has a lot of libraries that are needed for a lot of different things, depending on what the user decides to do.

The libraries are different depending on which content type is loaded. I want to only load the library ONCE when a user loads a content type for the first time.

Using the below code the library is attached every time the content type gets loaded. Leading to multiple instances of each library. 

function mytheme_preprocess_node(&amp;$variables) {
    $node = $variables['node'];
    switch($node-&gt;getType()){
        case 'nodeone':
            $variables['#attached']['library'][] = 'mytheme/liba';
            break;
        case 'nodetwo':
            $variables['#attached']['library'][] = 'mytheme/libb';
            break;
        case 'nodethree':
            $variables['#attached']['library'][] = 'mytheme/libc';
            break;
        default:
            break; 
    }
}


I can't do a preproccess_page as the content types are loaded asynchronously and would imply loading everything at once. I can't attach the library to the twig template as again, it happens at the node level, not the page. I have tried to attach the library to a view template, but the same issue remains, it gets loaded multiple times. 

If I could do some form of check to see if the library has already been loaded, I think that would be sufficient.
EDIT: Sorry didn't see you were doing it via AJAX, my below example might not be the same. But the theory of the JS triggering multiple times rather than the actual files loading might still be valid

I don't think it's the piece of code you've showed is causing your issue. Is the  library files definitely getting loaded multiple times into the source code? Or is it that the effects of the library are happening multiple times? (e.g. a JS being trgiggered multiple times) as thats a different issue

Drupal handles this situation and when it aggregates all the required libraries so any duplicates are removed. For example I'm just working on a news listing page that has 10 nodes coming out and just replicated your code to print "hi" add a library and the "hi" comes out 10 times but the library files only once