如果你想用 jQuery 在 <head> 标签内插入 <script>,但要确保它插入在 <title> 标签之前,可以使用以下方法:
.before() 方法如果 <head> 里已经有 <title>,可以用 $('title').before() 插入 <script>:
var script = $('<script>', {
src: 'https://example.com/your-script.js',
type: 'text/javascript'
});
$('title').before(script); // 在 <title> 之前插入 <script>
<head> 的开头(如果 <title> 是第一个元素)如果 <title> 是 <head> 的第一个子元素,可以直接用 $('head').prepend():
var script = $('<script>', {
src: 'https://example.com/your-script.js',
type: 'text/javascript'
});
$('head').prepend(script); // 插入到 <head> 的最前面
如果 jQuery 不可用,可以用原生 JS 实现:
var script = document.createElement('script');
script.src = 'https://example.com/your-script.js';
script.type = 'text/javascript';
var title = document.querySelector('title');
if (title) {
title.parentNode.insertBefore(script, title); // 在 <title> 之前插入
} else {
document.head.appendChild(script); // 如果没有 <title>,直接插入 <head>
}
确保 <title> 存在:如果 <head> 里没有 <title>,$('title').before() 会失效,此时应该用 $('head').prepend()。
避免重复加载:如果脚本可能被多次插入,建议先检查是否已存在:
if (!$('script[src="https://example.com/your-script.js"]').length) {
$('title').before(script);
}
异步加载:如果需要异步加载,可以添加 async 或 defer 属性:
var script = $('<script>', {
src: 'https://example.com/your-script.js',
async: true
});
完整示例
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
var script = $('<script>', {
src: 'https://example.com/your-script.js',
type: 'text/javascript'
});
$('title').before(script);
});
</script>
</body>
</html>
如果你想使用 jQuery 查找 <head> 标签内 id 为 test 的 <script> 标签,可以使用以下方法:
方法 1:直接使用 $('head script#test')
var script = $('head script#test');
if (script.length) {
console.log('找到 script:', script[0]);
} else {
console.log('未找到 id="test" 的 script');
}
$('head script#test') 查询 <head> 下的 <script id="test">。
script.length 检查是否找到匹配的元素(length > 0 表示找到)。
script[0] 获取原生的 DOM 元素(也可以用 script.get(0))。
find() 方法
var script = $('head').find('script#test');
if (script.length) {
console.log('找到 script:', script[0]);
} else {
console.log('未找到 id="test" 的 script');
}
$('head').find('script#test') 先选中 <head>,再查找其内部的 <script id="test">。
适用于更复杂的查找条件(如 $('head').find('[id="test"]'))。
如果你不想用 jQuery,可以用原生 JS:
var script = document.querySelector('head script#test');
if (script) {
console.log('找到 script:', script);
} else {
console.log('未找到 id="test" 的 script');
}
| 方法 | 代码 | 适用场景 |
|---|---|---|
| 直接选择器 | $('head script#test') |
简单直接 |
find() 方法 |
$('head').find('script#test') |
适用于更复杂的查找 |
| 原生 JS | document.querySelector('head script#test') |
无 jQuery 依赖 |
如果你只需要检查是否存在该 <script>,可以用:
if ($('head script#test').length) {
console.log('存在 id="test" 的 script');
}