Quantcast
Channel: Issues for Drupal core
Viewing all articles
Browse latest Browse all 296232

drupal modules: how can I access/inject external javascript objects into my custom javascript at runtime

$
0
0

I am looking for the recommended Drupal 'import' or 'require' functionality to include Javascript objects in Javascript files.

I want to add some custom.js to a module using libraries.yml file and in custom.js I want to access objects defined in 2 libraries.yml files: external.js and mylibrary.js. Libraries.yml loads the assets but doesn't appear to inject into the custom.js drupal behavior at run-time. Drupal appears to offer some kind of javascript module management by injecting jquery dependencies into a behaviour, but how so i inject js objects?

my-module.libraries.yml

  custom-library:
  version: 1.x
  js:
    # external.js defines external_js_object
    https://cdnjs.com/external.js : { type: external, minified: false }
    # a local library file
    js/mylibrary.js: {}      
    # custom.js uses objects from mylibrary.js and custom.js
    js/custom.js: {}
  dependencies:
    # these are injected into the drupal behaviour
    - core/jquery
    - core/drupal

js/custom.js

    (function ($, Drupal) { 
    Drupal.behaviors.custom_styles = {
      attach: function (context, settings) {
        // this works ok because jquery is injected into the behaviour
        $(".somediv").text("whatever");

        // this doesnt work. how to inject the external_js_object? 
        external_js_object.run();

        // this doesnt work. how to inject the mylibrary_object? 
        mylibrary_object.run();
    }
   })(jQuery, Drupal);

so my question again is: how do i inject the external js objects from external.js file specified in the library.yml file into the custom.js file so i can work with it?

Does Drupal support injection of external.js objects in the same way it does drupal dependencies? If so what is the correct syntax for me to inject my external_js_objects into a drupal behaviour?

I realise this needs something like import statements or webpack to make it work, but Drupal appears to have done half the job in the libraries.yml file but the import isnt clear. How do/can I extend (function ($, Drupal) {...})(jQuery, Drupal) to make them available in my js code.

Can I use es6 imports without any additional package modules (e.g. webpack)? If so I do I map the files in libraries.yml to namespaces in custom.js? Specifically how do I import "https://cdnjs.com/external.js : { type: external, minified: false }" into my custom.js?

thanks


Viewing all articles
Browse latest Browse all 296232

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>