JavaScript function called with button onclick, fails with onload

892 Views Asked by At

I am trying to use an external JavaScript function in the body tag: <body onload=function()>

<!DOCTYPE html>
<html>
<meta charset="UTF-8">

<head>
    <script type="text/javascript" src="js/mqttws31.js"></script>

    <script type="text/javascript" src="js/Long.min.js"></script>
    <script type="text/javascript" src="js/ByteBufferAB.min.js"></script>
    <script type="text/javascript" src="js/ProtoBuf.min.js"></script>
    <script type="text/javascript" src="js/fs.js"></script>
    <script type="text/javascript" src="js/bundle.js"></script>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="cordova_plugins.js"></script>

</head>
<body onload ="heartbeat()">

<h2>A demo for showing the pub/sub between clients and the message     broker</h2> <h3>IoTGateway</h3>
Topic :
<input type="text" name="pub"/>
Message:
<input type="text" name="pub"/>
<button onclick="connect()">
    Connect
</button>
<br>
<button onclick="publish()">
    Publish
</button>
<br>

<h3>BluetoothID</h3> Topic:
<input type="text" name="sub"/>
<button onclick="heartbeat()">
    Subscribe
</button>
<br>
<p id = "test"></p>
<p id="sub"></p>
<script>
        function heartbeat() {
            alert("hello");
            try{
            MqttPlugin.subscribe({topic: "$EDC/plugin"});
            }
            catch(err){
            alert(err.message);
            }
        }
       /* try{
        MqttPlugin.heartbeat({topic: "$EDC/tum/B8:27:EB:A6:A9:8A/HEARTBEAT-V1/mqtt/heartbeat"});
        }
        catch(err){
        alert(err.message);
        }*/



        function publish() {

            MqttPlugin.publish({
            topic:"$EDC/plugin",
            data:"Mqtt data"

            });
        }

        function subscribe() {
            MqttPlugin.subscribe({topic: "$EDC/plugin"});
        }



</script>
</body>
</html>

The function heartbeat is called when I call with the event onclick but fails with onload. In case of onload, it throws an error MqttPlugin not defined. Is it because by the time it calls the function, the js files are not loaded? Could someone help me fix this?

1

There are 1 best solutions below

3
On BEST ANSWER

I believe that your basic aim here is to subscribe to a topic automatically when the page is loaded. You can either try:

</script>
<style onload="heartbeat()"></style>
</body>

Or try changing the order of imports.

The first suggestion is just an hack not a full proof solution though.

The basic problem is that the heartbeat function is getting called before cordova_plugins.js is getting loaded. So either delaying the function call or loading the file early will do the trick.

Edited:

This jQuery method might just be the solution:

$( window ).load()

Please find documentation here.