0

I have a webpage to be hosted on a mobile device which is both Wi-Fi and 3G capable.

As 3G data may cost money and is generally limited, i want to minimize the amount of uploaded data by the device. So what I basically want to do is the following:

Try to load the jquery scripts online:

<script type="text/javascript" src="http://code.jquery.com/ui/1.8.13/jquery-ui.min.js"></script>

And only if that fails to load correctly (e.g. if the user is not connected to the internet, just to the phone), load it from a local copy:

<script type="text/javascript" src="js/jquery-copy.js"></script>

The same applies for css files.

I've thought about having a <script id="loadable"></script> and then use $("#loadable").load("url"); but obviously I depend on jquery to be loaded first, which is the file to be minimized.

Twinone
  • 2,949
  • 4
  • 28
  • 39

3 Answers3

2
 <script src="http://code.jquery.com/ui/1.8.13/jquery-ui.min.js"></script>
 <script>!window.jQuery && document.write(unescape('%3Cscript src="js/jquery-copy.js"%3E%3C/script%3E'))</script>
PSR
  • 39,804
  • 41
  • 111
  • 151
  • I'm gonna mark your question as answer, just because you were the 1st to provide a working solution, but i must say I don't like the begging comment. – Twinone Mar 02 '13 at 10:15
1

I edited the answer. I think bellow is the most elegant solution.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">window.jQuery || document.write('<script type="text/javascript" src="path/to/your/jquery"><\/script>')</script>

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

Community
  • 1
  • 1
Alqin
  • 1,305
  • 3
  • 16
  • 35
0

check out how they do it in HTML5 boilerplate.

If you take a look at the bottom of the index.html file within the GitHub repo, you'll see the following...

 <script src="http://code.jquery.com/ui/1.8.13/jquery-ui.min.js"></script>
     <script>!window.jQuery && document.write(unescape('%3Cscript src="js/jquery-copy.js"%3E%3C/script%3E'))</script>

How does it work?

  • First, an attempt is made to grab the CDN version (Google's CDN url is used above, but of course you could link to any source you like).

  • Immediately afterwards, we check for the jQuery global object.

  • If jQuery does not exist, the obvious assumption is that we didn't manage to get the code from the CDN, so then we document.write a script tag to get a copy from a local source instead.

Sahil Popli
  • 1,967
  • 14
  • 21
  • 1
    -1 if you're going to reference h5bp, _use_ the code that's in the file you're pointing at as a reference. h5bp's index doesn't include jquery **UI** from a cdn; it uses a protocol-relative url; and it doesn't needlessly encode and unescape the string to be written (the script tag). If the code were copy+paste usable, I wouldn't have commented, but it isn't. – AD7six Mar 02 '13 at 20:59