0

Basically, I want to do this:

<script src=" path + '/jquery.js'"></script>

(Obviously that won't work.)

I have a standalone page loading external scripts with <script>, but the URL needs to be prefixed with the variable path (because the page is run on different servers in different environments). I easily get path from the URL which always ends with "?path=X" where X is the actual path.

If I had jQuery, I know I could use getScript() to dynamically load external .js files, but jQuery is one of the files I need to load! I don't need anything too complicated here, no need to worry about encoding or file-types, it's a fairly simple situation except for the changing servers.

5
  • 1
    is it not possible to just load jquery from a cdn? Or is that not an option? Commented Oct 29, 2012 at 18:58
  • Not an option, it might be loaded on a system without a real connection to the internet. Commented Oct 29, 2012 at 19:04
  • Shouldn't you also be checking if jQuery is already included, as to not break the page you are including your script on? or do you not care about that. Commented Oct 29, 2012 at 19:04
  • @KevinB It is a standalone page and I can't see any way that jQuery could already be included. I haven't included it. Am I missing something obvious? Commented Oct 30, 2012 at 16:46
  • @brentonstrine Sorry, i missed that it is a standalone page, not script. Commented Oct 30, 2012 at 17:07

2 Answers 2

5

You need to use plain javascript if jquery not loaded. Something like that:

        var fileref=document.createElement('script');
          fileref.setAttribute("type","text/javascript");
          fileref.setAttribute("src", path + '/jquery.js');
          document.getElementsByTagName("head")[0].appendChild(fileref);
          fileref.onload = function(){alert('loaded')};
Sign up to request clarification or add additional context in comments.

2 Comments

is this asynchronous? or would i have to test to see when the jquery is finished loading?
asynch by default if from other domain, if same domain should be sync i think, see my edit
1

You can load JS files by inserting them into the head with javascript, and at the same you can use your variable for the path when setting the source attribute:

<script type="text/javascript">
    var script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.src = path + '/jquery.js';
    var head = document.getElementsByTagName('head')[0];
        head.appendChild(script);
</script>

Comments

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.