Doug Fir
Doug Fir

Reputation: 21204

load js library from within a function?

I have only ever loaded in a JS library in the head of an html doc like so

<head>
<script src="somelink.js" />
</head>

My question is, can I load this script from within a function and if so what would that look like?

function() {
src="somelink.js"
return somemethod.bla;
}

Would that work? Presumably not.

I have my reasons for wanting to do this but will leave them out of the question for now.

Is it possible to load in a library from within a function and if so what would that look like?

Upvotes: 4

Views: 117

Answers (2)

Ritesh  Karwa
Ritesh Karwa

Reputation: 2254

Try this :

  <!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>load demo</title>
  <style>
  body {
    font-size: 12px;
    font-family: Arial;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<b>Successful Response (should be blank):</b>
<div id="success"></div>
<b>Error Response:</b>
<div id="error"></div>

<script>
$( "#success" ).load( "somelink.js", function( response, status, xhr ) {
  if ( status == "error" ) {
    var msg = "Sorry but there was an error: ";
    $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
  }
});
</script>

</body>
</html>

Upvotes: 1

sissonb
sissonb

Reputation: 3780

Here's how it's done in script.js. https://github.com/ded/script.js/

var el = doc.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
  if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
    return false;
  }
  el.onload = el.onreadystatechange = null;
  loaded = true;
  // done!
};
el.async = true;
el.src = "script-to-load.js";
document.getElementsByTagName('head')[0].insertBefore(el, head.firstChild);

If you use the script.js library then you can load a script like this.

$script('script-to-load.js');

Upvotes: 0

Related Questions