简体   繁体   English

如何将jQuery脚本附加到head标签

[英]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. 当窗口大小小于580px时,我试图在head标签中附加带有src属性的jQuery脚本。

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="". 我认为问题是src =“”。 What am I supposed to do? 我应该做些什么?

I see 2 problems with this code: 我看到此代码有2个问题:

1) You are using jQuery syntax in your script block to add a reference to load jQuery? 1)您正在脚本块中使用jQuery语法来添加引用以加载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. 除非您已经在某处加载了jQuery副本,并且出于某种原因试图使用此代码将其更新为其他版本,否则这将无法工作。

2) I see you are escaping the " like so: \\" in your first example. 2)我看到您在第一个示例中转义了" like like: \\" You DO NOT need to do that in jQuery, assuming issue 1 is not really an issue or resolved. 假设问题1并非真正的问题或已解决,则您无需在jQuery中执行此操作。 jQuery will properly handle double quotes inside a single quote or vice versa. jQuery将正确处理单引号内的双引号,反之亦然。

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);

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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