cancel
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");
element.src="defer.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>

 

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!

2 REPLIES 2

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.src=url;
    script.async = true; // < defer

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

and after it

 

dynamicLoadScript("defer.js");

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.