Download js library from function?

I only ever loaded into the JS library in the header of an html document like this:

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

My question is: can I load this script from a function, and if so, what will it look like?

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

Will this work? Presumably not.

I have reasons for this, but this time they will not be discussed.

Is it possible to load functions into the library from within, and if so, how will it look?

+4
source share
2 answers

Try the following:

  <!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>
+1
source

This is how it is 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, you can load a script like this.

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

All Articles