0

I'm trying to run this library ParticleJS which requires me to download a Json.

I added this file into theme/libraries.yml this way:

global-js:
  js:
    assets/js/particles.min.js : {}
    assets/js/particles.json : {}

But that gives me this error:

Refused to execute script from 'https://www.example.com/themes/nexus/assets/js/particles.json?pem8cm' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

So I'm added:

<script src="themes/nexus/assets/js/particles.json"></script>

And it is giving me the same error.

Can someone help me with this problem, please? How should I include any other file into twig templates? Thank you

1
  • 1
    What you're trying to do isn't possible the way you're trying to do it - <script> tags are just for loading scripts, you can't source a JSON file that way. Even if you could, what would you expect to happen? How would the browser know what you intended to do with the loaded object? You'll need to either pre-build the JS file with the object already in it, or load it via AJAX and manipulate it that way
    – Clive
    Sep 6, 2018 at 7:36

2 Answers 2

2

You need use hook_page_attachments_alter

function mytheme_page_attachments_alter(&$attachments){
  $attachments['#attached']['html_head'][] = [
    // The data.
    [
      '#type' => 'html_tag',
      // The HTML tag to add, in this case a  tag.
      '#tag' => 'script',
      // set attributes like src to load a file
      '#attributes' => array('src' => '/themes/mytheme/assests/js/particles.json'),

    ]
  ];

}
2
  • Where should I add this code? Which file?
    – DarkteK
    Sep 6, 2018 at 6:09
  • 1
    add your themes yourtheme.theme
    – vinhdv
    Sep 6, 2018 at 6:16
1

I would load it with javascript on the front-end

According to the example in the GitHub Page, this javascript should work:

/* particlesJS.load(@dom-id, @path-json, @callback (optional)); */
particlesJS.load('particles-js', '/themes/nexus/assets/js/particles.json', function() {
  console.log('callback - particles.js config loaded');
});

In general, you could use this:

(function($){
  $.get( "/themes/nexus/assets/js/particles.json", function( data ) {
    console.log(data);
    alert( "Data Loaded: " + data );
  });
})(jQuery);

Also, note that the best practice is to encapsulate your JS in Drupal Behaviors, as described in the Drupal JS API, but it has a learning curve. In your case, it should work just as it is in the example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.