4

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?

asked Jun 19, 2015 at 19:03

2 Answers 2

1

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>
answered Jun 19, 2015 at 19:06
Sign up to request clarification or add additional context in comments.

Comments

0

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');
answered Jun 19, 2015 at 19:06

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.