简体   繁体   中英

Cant add jquery to the head dynamically and run jquery code

I have got this code:

function init(){
    if (typeof window.jQuery !== 'function') {
        var link = document.createElement('script');
        link.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
        document.getElementsByTagName('head')[0].appendChild(link);
    }
}

window.onload = init;

 if (typeof window.jQuery === 'function')  {
    $(document).ready(function(){
        alert(1);
    });
}

What I am trying to do is to add jquery script link to the head if jQuery doesnt exist and then run the code. What could be best is to check whether jquery exists in the head as soon as possible and then add a link to the source. But I dont know how to achieve so?

UPDATE: An alternative approach would be using a function:

  function init(){
   if (typeof window.jQuery !== 'function') {
      var link = document.createElement('script');
      link.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
      document.getElementsByTagName('head')[0].appendChild(link);
      start_code();
   }
   else{
       start_code();
   }
}  
window.onload = init;
function start_code(){
           $(document).ready(function(){
                alert(1);
           });
     }

I could basically call a function after everything is loaded.. But this doesnt work well. cause the $ is not defined error is being thrown too

function init(){
   if (typeof window.jQuery !== 'function') {
      var link = document.createElement('script');
      link.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
      document.getElementsByTagName('head')[0].appendChild(link);
   }
}

or use the HTML5 boilerplate approach

<script>window.jQuery || document.write('<script src="/js/vendor/jquery-1.7.2.min.js"><\/script>')</script>

placing this script at the bottom of the page (for performance purpose). Then, if you need to use jQuery function before, just take a look at this resource: stop paying your jQuery tax

since document.write here is creating a script block (which is synchronous) all you have to do is simply

<script>window.jQuery || document.write('<script src="/js/vendor/jquery-1.7.2.min.js"><\/script>')</script>
<script>
    $(document).ready(function(){
        alert(1);
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM