javascript - 我是否应该转换内联脚本以便将其放入外部 .js 文件?

标签 javascript jquery html css

我是 jQuery 的新手,我一直在我的网页中使用 koga73 ( https://github.com/koga73/SnapScroll ) 的 SnapScroll jQuery 插件。

它要求我使用内联脚本:

<script> 
var snapScroll = $("header, section, footer").SnapScroll({
hashes:true }); console.log(snapScroll);

$("header").on(snapScroll.eventChangeActive, function(evt, newActive){
console.log(evt, newActive);
});

$(document).on(snapScroll.eventChangeVisible, function(evt, visibleList){
console.log(evt, visibleList.data);
});
</script>

它一直运行良好,但我只是想知道是否值得将它移到外部 .js 文件中,如果是这样,我如何将代码转换为在外部 .js 文件中工作?

我的外部 js 文件是:

<script type="text/javascript" src="web/js/init.js"></script>    

最佳答案

通常,您希望将所有 JavaScript 放在外部文件中 - 内联对于调试和开发非常有用,但当您投入生产时,总是一个经过缩小和压缩的外部文件 - 不过,您可能会担心最后两个。

如果您将该代码放在一个文件中,您希望像这样放置该代码... ..并丢失脚本标签

// A $( document ).ready() block.

$(document).ready(function() {
    var snapScroll = $("header, section, footer").SnapScroll({
    hashes:true }); console.log(snapScroll);

    $("header").on(snapScroll.eventChangeActive, function(evt, newActive){
        console.log(evt, newActive);
    });

    $(document).on(snapScroll.eventChangeVisible, function(evt, visibleList){
        console.log(evt, visibleList.data);
    });
});

//OR
// Shorthand for $( document ).ready()

$(function() {
    //your code here
});

然后,在页面底部插入您的外部脚本链接。

关于javascript - 我是否应该转换内联脚本以便将其放入外部 .js 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54702466/

相关文章:

javascript - 提交前修改表单数据

javascript - Angular ngClass 幽灵类

javascript - 读取 json 并在鼠标悬停时显示动态值

javascript - 根据 div 的可用高度显示省略号

jquery - 如何使用 JQuery 根据存储在其他 TD 中的表的值替换第一个 TD 中的文本?

jquery - 隐藏 HTML 复选框,但在使用自定义图像复选框时保持功能

javascript - AJAX On Keyup 搜索功能

java - 如何在单击按钮时导出到 .excel 时添加 openwith 并另存为对话框

javascript - 在javascript中滚动时放大缩小图像

html - 如何确保一个 radio 表格不检查另一个 radio 表格