I have the following code which when embedded within a loaded html page works successfully:
<HEAD>
<script language="javascript" type="text/javascript">
document.addEventListener('DOMContentLoaded', function ()
{
document.documentElement.addEventListener("touchstart", function (e)
{
if (['A', 'BUTTON'].indexOf(e.target.tagName) === -1)
{
e.preventDefault();
e.stopPropagation();
invokeObjectiveC("ontouchstart:");
}
else
{
e.preventDefault();
e.stopPropagation();
invokeObjectiveC(e.target);
}
}, true);
}, false);
function invokeObjectiveC(action) {
...
}
However if I take it out of the html and try to load it separatly then it is not working. When loading it separately it looks like this:
alert('test');
function addListener()
{
alert('adding listener');
document.addEventListener('DOMContentLoaded', function ()
{
document.documentElement.addEventListener("touchstart", function (e)
{
alert('touchstart');
if (['A', 'BUTTON'].indexOf(e.target.tagName) === -1)
{
e.preventDefault();
e.stopPropagation();
invokeObjectiveC("ontouchstart:");
}
else
{
e.preventDefault();
e.stopPropagation();
invokeObjectiveC(e.target);
}
}, true);
}, false);
}
addListener();
function invokeObjectiveC(action) {
...
}
When added, a "test" and an "adding listener" alert dialog are displayed so I know this part is working. However the code then doesn't work - its supposed to detect touches (this is on iOS) in certain parts of the screen. With the code within the html everything works fine and it executes when the screen is touched, when its loaded separatly nothing happens when the screen is touched. Any ideas what the problem could be?
====== UPDATE I tried running the following during various stages of the lifecycle, including before the request to even load the page has been issued, but 'Dom content loaded' never appears:
var script = document.createElement('script');
script.type = 'text/javascript';
script.text =
var Test =
{
f: function()
{
if (!event.originalTarget.defaultView.frameElement)
{
alert('DOM content loaded');
}
}
}
function addTestListener()
{
alert('adding listener');
window.addEventListener("DOMContentLoaded", function(e) { Test.f(); }, false);
}
document.getElementsByTagName('head')[0].appendChild(script);