简体   繁体   中英

How to append a jQuery script to head tag

I'm trying to append a jQuery script with src attributes in my head tag when the window size is less of 580px.

I try with this code:

<script>
    $(document).ready(function(){
        var windowSize = $(window).width();
        if( windowSize > 300 && windowSize < 570) {
            $('head').append('<script src=\"http://code.jquery.com/jquery-1.11.3.min.js\" type="text/javascript\"><\/script>');     
        }
    });
</script>

But it seems it doesn't work. Instead, I put inside the script a simple alert and it works:

<script>
    $(document).ready(function(){
        var windowSize = $(window).width();                 
        if( windowSize > 300 && windowSize < 570) { 
            $('head').append('<script>alert("hi");<\/script>');
        }
    });
</script>

I think the problem is the src="". What am I supposed to do?

I see 2 problems with this code:

1) You are using jQuery syntax in your script block to add a reference to load jQuery? This will NOT work unless you already have a copy of jQuery loaded somewhere and are trying to use this code to update it to something else for some reason.

2) I see you are escaping the " like so: \\" in your first example. You DO NOT need to do that in jQuery, assuming issue 1 is not really an issue or resolved. jQuery will properly handle double quotes inside a single quote or vice versa.

This is old school lession

function loadScript(url, callback){ 
   var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(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