0

I have the following in my html

<html>
<body>
<script type="text/javascript">
 var hccid=98964571;
 function add_chatinline(){
    var nt=document.createElement("script");
    nt.async=true;
    nt.src="http://localhost/ll.js";
    var ct=document.getElementsByTagName("script")[0];
    ct.parentNode.insertBefore(nt,ct);
    console.log("state is ", SORCHAT)//SORCHAT is not defined
 }
 add_chatinline();
 </script>
</body>
</html>

On the ll.js i have

var SORCHAT = SORCHAT || (function () {
return {
    init: function (Args) {
        console.log("hash is ", Args)
    },
};
}());

But now am getting an error of SORCHAT is not defined.

By adding window.onload that is

 <script>
  window.onload = function(){
    SORCHAT.init(12736474676); //this works
 } 
 </script>

But whenever i include another javascript file with window.onload function the SORCHAT.init is not executed.

What am i missing.

Geoff
  • 4,505
  • 14
  • 65
  • 156
  • Possible duplicate of [Add two functions to window.onload](https://stackoverflow.com/questions/16683176/add-two-functions-to-window-onload) – Heretic Monkey May 26 '19 at 12:39

1 Answers1

2

You are probably overwriting the window.onload when using it multiple times. You can prevent that with the help of the addEventListener-function.

window.onload = function () {
  console.log('onload #1');
}
window.onload = function () { // This replaces the first onload (#1)
  console.log('onload #2');
}

window.addEventListener('load', function () {
  console.log('onload #A');
});

window.addEventListener('load', function () {
  console.log('onload #B');
});
Jan
  • 2,744
  • 2
  • 18
  • 25