Developer: Non-blocking and “non-loading” script (lazy loading)

Signup for a free 18-days trial today

Developer: Non-blocking and “non-loading” script (lazy loading)

In Knowledge base >

This is an example how to make the javascript load after the browser have loaded all your website information. Thus the chat is not displayed until the full page has been loaded. This is great in cases where you want your website to not look like it is slow because of slow connection to external scripts.

To do lazy loading of javascript, you have to make the script load first when the page has send the “all loaded” event (onload). We do it by adding an event listener to the window. With webkit (Chrome/Safari), we experienced that this still didn’t work, so we added a one milisecond timeout to make sure that it calls the function right after the event.

This works in all modern browsers (tested in IE 9, Chrome 26, Safari 6, Firefox 19).

Here’s the example on how you do it. The added lines is marked, and as you can see you just have to split up the cSupport script, and add parts of it inside a function.

<script type="text/javascript">
		var scrs=d.getElementsByTagName("script");var scr=scrs[scrs.length-1];
		var w=window;
		function n(){
			var e=d.createElement("script");e.async=true;e.src=("https:"==document.location.protocol?"https://":"http://")+""+scrs.length;
			if(typeof c=="function")if(e.addEventListener)e.addEventListener("load",c,false);else if(e.readyState)e.onreadystatechange=function(){if(this.readyState=="loaded")c();};
		function s(){f=w.setTimeout(n,1);};
		if (w.attachEvent) w.attachEvent('onload', s);
		else w.addEventListener('load', s, false);