We help IT Professionals succeed at work.

Preventing JS script element from hanging

monoceros
monoceros asked
on
Hi,
Recently hit an issue on a mobile e-commerce site where a very slow response from 3rd party site caused the execution of our JS to be delayed for long enough that the site appeared to be down (we load product information using JS/ajax).

The basic flow is:

in head we load our site JS
in the body we load a script for click tracking using (all identifying parameters removed to protect the 3rd party:
	<script type='text/javascript'>
			document.write('<script src="http://the.trackingcompany_X.com/x/y?"></script>');
	</script>

Open in new window


This then returns with further JS that includes
var part_0 = '';part_0 += "<"+"script type=\"text/javascript\" src=\"http://tracking.company_Y.com/releases/collector.js\"><"+"/script>\n";part_0 += "<"+"script type=\"text/javascript\">\n";part_0 += "window.company_Y.collectorController.recordEngagementEvent(\'menu-xxxxx-page\', 0);\n";part_0 += "<"+"/script>\n";document.write(part_0);

Open in new window


The issue is that http://tracking.company_Y.com/releases/collector.js was not responding in a timely manner and so the rest of the page JS execution is delayed and the site seemed to be down.

So we are looking to add some defensive programming into the site. I would like to wrap the outer script with some defensive programming.

Would something like (obviously without the alerts)
<script type="text/javascript">
var jsLoaded = false;
setTimeout("callback()", 2000);
function callback() {
    if (!jsLoaded) {
        alert("Javascript not loaded after 2 seconds!");
    } else {
        alert('Loaded');
    }
}
</script>
<script type="text/javascript" id="foo" src="url.js" onload="jsLoaded=true"></script>

Open in new window


... be well supported across mobile browsers?

Is there a better way?
Comment
Watch Question

Manager / Solutions Architect
Commented:
I don't know what you're actaully doing inside that script file but I think using the async or difer attributes might be the supported solution for you.
http://www.w3schools.com/tags/att_script_async.asp

Basically the difference between the them is:
Not using them: The DOM parsing pauses while a script file is loading and executing.

Async: the script file loads in parallel with the DOM parsing and is executed right after the loading, pausing the parsing just while executing.

Defer: The script file loads in parallel with the DOM parsing and is executed at the end of the DOM parsing.

Here's a nice illustration: http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html

If I understood correctly, this script is not core to the application, and you don't want the user to be affected by it.
In this case I would go for the Defer.

Author

Commented:
Thanks, defer worked for my target devices - I had dismissed it based on warnings about lack of support - but it seems fine.