Conditional loading of jQuery

javascript, jquery

Solution

This is a case where it may make sense to use `document.write()`. You'd need to put this code in the `<body>` instead of the `<head>`:

  <script type="text/javascript">
    var canvas = document.createElement('canvas');
    if (canvas && canvas.getContext && canvas.getContext('2d')) {
      document.write( '<script src="js/jquery.js"><\/script>' );
    }
    else {
      // ... redirection ...
    }
  </script>
  <script type="text/javascript">
    $(function () {
      //...
    }
  </script>

Or, you may be able to use an ordinary `<script>` tag to load jQuery, but put it after your conditional redirection:

  <script>
    var canvas = document.createElement('canvas');
    if( !( canvas && canvas.getContext && canvas.getContext('2d') ) ) {
      // ... redirection ...
    }
  </script>
  <script src="js/jquery.js"></script>
  <script>
    $(function () {
      //...
    }
  </script>

With either of these approaches, the order of execution is:

- The first `<script>`.

- The loading of `jquery.js`, whether done with `document.write()` or a simple `<script>` tag.

- The final script.

Problem

I am testing with pure JavaScript if browser seems to support HTML5 and if so, I want to load jQuery and then process the rest of page. If not, some redirection will occur. ``` <script type="text/javascript"> var canvas = document.createElement('canvas'); if (canvas && canvas.getContext && canvas.getContext('2d')) { var s = document.getElementsByTagName('script')[0]; var jq = document.createElement('script'); jq.type = 'text/javascript'; jq.src = 'js/jquery.js'; s.parentNode.insertBefore(jq, s); } else { // ... redirection ... } </script> <script type="text/javascript"> $(function () { //... } </script> ``` But the code above is not working properly, because I got error ``` Uncaught ReferenceError: $ is not defined ``` which is clearly saying that jQuery library has not been loaded. Why? What is wrong with conditional script loading in my code above?

Original source

Related problems