1

I'm working on a kiosk-type plugin which will cycle through all news entries, beginning upon template (or page) load.
It needs to load a JavaScript ajax script for this on page/template load.

Would body onload work within a template, or would something more Craft-specific be required?

Thanks for any leads!

1

While there is no reason it wouldn't work using the onload attribute of the <body> element, you could also consider using a twig {% js %} tag.

The {% js %} tag allows you to register JS to be added in your page from anywhere in your template. By default it will be added at the end of the <body> element, which guarantees your HTML document is loaded when the JS is executed.

Exemple:

{% js %}
  console.log('document loaded');
{% endjs %}

The main drawback of this approach is that the JS will be part of your HTML page source so it might be repeated on several pages depending on where you call it in your template.

There are many other (better) ways to do this but they're not Craft specific.

1
  • Is {% js %} the Craft 3 equivalent of {% includeJs %} in Craft 2?
    – buck1112
    Sep 15 at 20:06

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.