Showing results for 
Search instead for 
Did you mean: 

Defer Javascript

Defer Javascript

Dear Magento users,


I have currently a question concerning the deferral of Javascript. I would like to use this code in order to defer javascript:


<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;


I would like to paste this code just before the </body> tag. Therefore I would like to inquire what I have to do in order to realize it.


Thanks in advance!


Re: Defer Javascript

I use my function before closed </body>


function dynamicLoadScript(url) {
    if (!url) return;

    var script = document.createElement("script");

   script.type = "text/javascript";
    script.async = true; // < defer

    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script);

and after it



Re: Defer Javascript

Hi @Miaku_UG


Magento 2 uses RequireJS to load its Javascript components. I suggest taking a look at the indepth intro from Alan Storm here.


Since RequireJS offers lazy loading defering would not be needed.