Leo
Leo

Reputation: 4428

Need to load javascript library or just wait for it to load?

I load a javascript library when a user clicks a button:

if (mylib.myfunction) {
    mylib.myfunction();
} else {
    var jsElt = document.createElement("script");
    body.head.appendChild(jsElt);
    jsElt.onload = function() { mylib.myfunction(); }
    jsElt.src = MYLIB_URL;
}

That works, of course, but there is a problem: If the user clicks a second time before the onload event the else-part will be executed again. What is the best way to avoid this? A local variable? Something else?

UPDATE: I want to thanks @Suman Bogati and @usernid for their suggestion to disable the button that was clicked. However that solution is too limited for me because it assumes that you have access to the button from the code loading the new library. That is not always the case, of course.

In my case I can't use this solution so I will use a global variable instead. If no one has a better idea. ;-)

Upvotes: 1

Views: 167

Answers (3)

Brian McGinity
Brian McGinity

Reputation: 5935

This might work, I have not tested:

if (mylib.myfunction) {
    mylib.myfunction();
} 
else {
   if (!document.getElementById("scriptTag") ) {
      var jsElt = document.createElement("script");
      jsElt.onload = function() { mylib.myfunction(); }
      jsElt.setAttribute("id", "scriptTag");       }
      jsElt.setAttribute("src", MYLIB_URL);
      body.head.appendChild(jsElt);
}

Upvotes: 0

Suman Bogati
Suman Bogati

Reputation: 6349

Disabled the button until your script is loaded, something like this

DEMO

<button onclick="loadJavascript()" id="myButton">Load js</button>

<script>
function loadJavascript(){
    var myButton = document.getElementById('myButton');
    myButton.disabled = true;
    var jsElt = document.createElement("script");
    document.head.appendChild(jsElt);
    jsElt.onload = function() { 
        myButton.disabled = false;
        //mylib.myfunction(); call your function here
    }
    //here your src for js file, this is just testing purpose
    jsElt.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
}
</script>

Upvotes: 0

Alex Man
Alex Man

Reputation: 4886

try

to disable button from script

document.getElementById("btnId").disabled = true; 

to enable button from script

document.getElementById("btnId").disabled = false; 

and in your code...

function methodName()
{

  document.getElementById("btnId").disabled = true; 
  if (mylib.myfunction) {
      mylib.myfunction();
      document.getElementById("btnId").disabled = false; 
  } else {
      var jsElt = document.createElement("script");
      body.head.appendChild(jsElt);
      jsElt.onload = function() { mylib.myfunction(); }
      jsElt.src = MYLIB_URL;
      document.getElementById("btnId").disabled = false; 
  }
}

html

<input type="button" id="btnId" value="CLICK" onclick="methodName()">

Upvotes: 1

Related Questions