0

I have an idea where I would like to load jQuery (via CDN) into a JavaScript file that when called on the page loads jQuery via the CDN and also loads the JavaScript file. so instead of doing:

<script>jquery</script>
<script>myscript></script>

I would just do:

<script>myscript</script>

and then jQuery would just load.... Because in the myscript.js I would be doing something like: call jQuery via CDN .... do js code here that uses jQuery ...

3
  • So where is the problem? Simple approach: Just insert <script> tag for jQuery. Commented Sep 13, 2013 at 15:34
  • @Sirko You can't do a <script> tag inside a .js file .... ?? Commented Sep 13, 2013 at 15:38
  • @LogicLooking I can do something like document.getElementById( 'target' ).innerHTML += '<script src="jquery.from.some.where"></script>';. Commented Sep 13, 2013 at 15:46

2 Answers 2

1

Although we can hope for a module solution in a near future, JavaScript currently doesn't allow for simple script dependency management.

You have a few solutions, the two main ones are :

  • you write in your code a script element
  • you use a library which manages dependencies like RequireJS

If you want to use RequireJS, then you'd better read the guide dedicated to importing jQuery.

Today, with the current state of the import management in browsers, I would generally recommend to be less ambitious and to simply import with a classical script element. But RequireJS is interesting and you might find it useful when your application grows.

Sign up to request clarification or add additional context in comments.

3 Comments

Damn I wanted to essentially write a library that sat on top of jquery to do some custom stuff but I didnt want people to have to go out and get jquery - I just wanted it all packaged as one
#1 sounds horrible; why would you suggest this?
@JanDvorak Well, it's common. Look at the other answer. I, at least, didn't give the code because I don't advocate using it (but it works).
0

Add this to your script:

document.write(unescape("%3Cscript src='/js/jquery-X.X.X.min.js' type='text/javascript'%3E%3C/script%3E"));

4 Comments

this will cause the browser to become unresponsive until jQuery is loaded.
While I agree with the downside, to my mind this is the solution to the question. I would certainly advocate using the CDN as it was intended, or bundling the library with the site.
@chris you can load asynchronously from a CDN.

Your Answer

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.