<p>While there is no reason it wouldn't work using the <code>onload</code> attribute of the <code>&lt;body&gt;</code> element, you could also consider using a twig <code>{% js %}</code> tag.</p>
<p>The <a href="https://craftcms.com/docs/3.x/dev/tags.html#js" rel="nofollow noreferrer"><code>{% js %}</code> tag</a> 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 <code>&lt;body&gt;</code> element, which guarantees your HTML document is loaded when the JS is executed.</p>
<p>Exemple:</p>
<pre><code>{% js %}
  console.log('document loaded');
{% endjs %}
</code></pre>
<p>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.</p>
<p>There are many other (better) ways to do this but they're not Craft specific.</p>

CC BY-SA 4.0
2021-09-15T20:06:28.350Z
Is `{% js %}` the Craft 3 equivalent of `{% includeJs %}` in Craft 2?
buck1112
CC BY-SA 4.0
2021-09-03T14:28:26.593Z
2021-09-03T14:28:26.593Z
nstCactus
<p>I'm working on a kiosk-type plugin which will cycle through all news entries, beginning upon template (or page) load.<br />
It needs to load a JavaScript ajax script for this on page/template load.</p>
<p>Would <code>body onload</code> work within a template, or would something more Craft-specific be required?</p>
<p>Thanks for any leads!</p>

<plugin-development><templating><ajax><craft2><javascript>
Loading JavaScript on Template Load
# Loading JavaScript on Template Load

(Asked by: username_0 on 2021-08-31)

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!

**Tags:** plugin-development, templating, ajax, craft2, javascript


---

## 1 answers

### Answer by username_1 on 2021-09-03. Score: 1

While there is no reason it wouldn't work using the onload attribute of the  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  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.

> **Comments:**
> **username_0**: Is `{% js %}` the Craft 3 equivalent of `{% includeJs %}` in Craft 2?  

---

