是否可以将 JavaScript 拆分到多个文件并相互访问函数

Is it possible to split JavaScript across multiple files and access functions from each other

本文关键字:文件 函数 访问 JavaScript 拆分 是否      更新时间:2023-09-26

我想做的是有一个JavaScript文件,其中包含跨多个站点使用的jQuery函数(所有站点都托管在同一个CMS - eTouches上,因此没有跨域脚本问题),然后为每个使用这些功能的站点都有一个特定于站点的JavaScript文件,从而可以轻松地根据需要更改中央功能文件。

不过,我在尝试执行此操作时遇到错误,当第二个脚本尝试执行内容时未定义函数。这是可能的,我错过了一些基本的东西还是不可能的事情。

我认为不可能像在 PHP 等中那样包含文件,但是如果我在特定于站点的文件之前调用函数文件,我认为这应该可以工作吗?

提前感谢任何帮助。

函数文档中的代码

$.noConflict();
jQuery(document).ready(function ($) {
$('<a href="#" class="mobile-menu-toggle-link">&#9776; Menu</a>').insertBefore($('.ehtm'));
if ($('#right_sidebar_section').length) {
} else {
    $('#main_section').css('width','100%')
    $('#main_section').css('marginLeft','0')
}
var mobileMenu = function (menuParent, prevSibling, menuIdentifier) {
    if ($('#mobileMenu').length == 0) {
        var $select = $('<div>', {
            'class': 'mobile-menu',
            'id': menuIdentifier
        }).insertBefore(prevSibling);
        $('.ehtm > ul').prependTo($('#mobileMenu'));
    }
    if ($('.expandContract').length==0) {
        $('.mobile-menu > ul > li > a').each(function(){
            $(this).css("width", "120px");
            $('<a href="#" class="expandContract">+<span></span></a>').insertBefore($(this));
        })
    }
    $('.expandContract').click(function (evt) {
        evt.preventDefault();
        $(this).text($(this).text() == '+' ? '-' : '+');
        $(this).parent().find("ul").slideToggle();
        evt.stopImmediatePropagation();
    })
};
var menuReset = function () {
    $('.mobile-menu > ul').prependTo($('.ehtm'));
    $('#mobileMenu').remove();
    if (parseInt($('#outer_table').css('margin-left')) > 0) {
        $('#outer_table').animate({
            marginLeft: parseInt($('#outer_table').css('marginLeft'), 10) == 0 ? 200 : 0
        });
    }
    $('a.expandContract').each(function(){
        $(this).remove();
    })
    $('.ehtm > ul > li > a').each(function(){
        $(this).css('width','auto');
    })
}
$('.mobile-menu-toggle-link').click(function (evt) {
    evt.preventDefault();
    $('#outer_table').animate({
        marginLeft: parseInt($('#outer_table').css('marginLeft'), 10) == 0 ? 200 : 0
    });
    $('.header').animate({
        marginLeft: parseInt($('#outer_table').css('marginLeft'), 10) == 0 ? 200 : 0
    });
    $('.mobile-menu').animate({
        marginLeft: parseInt($('#outer_table').css('marginLeft'), 10) == 0 ? 0 : -200
    });
    var wHeight = $(window).innerHeight();
    var divHeight = $('#mobileMenu').height();
    if (wHeight > divHeight) {
        $('.mobile-menu').css("height", wHeight);
    } else {
        $('.mobile-menu').css("height", divHeight);
    }
})
var compareWidth = $('.header').width();
/* Add class to the first table row, to allow header styling */
var headRow = $("table#outer_table").find("tr:first");
$(headRow).addClass("headerBGColor");
});

来自站点特定文档的代码

$.noConflict();
jQuery(document).ready(function ($) {
var compareWidth = $('.header').width();
var setUpPage = function () {
    if (compareWidth < 768) {
        mobileMenu('.ehtm li', '.header', 'mobileMenu');
    }
    if (compareWidth >= 768) {
        menuReset();
    }
    /* Header image swap */
    if (compareWidth>=1024) {
        $("#headerImage").attr("src","https://www.eiseverywhere.com/image.php?acc=xxx&id=xxxxxx");
    } else if ((compareWidth>=768) && (compareWidth<1024)) {
        $("#headerImage").attr("src","https://www.eiseverywhere.com/image.php?acc=xxx&id=xxxxxx");
    } else {
        $("#headerImage").attr("src","https://www.eiseverywhere.com/image.php?acc=xxx&id=xxxxxx");
    }
    /* Carousel */
    if ($('.owl-carousel').length > 0) {
        $('.owl-carousel').owlCarousel({
            items:1,
            loop:true,
            margin:10,
            autoplay:true,
            autoplayTimeout:3000,
            dots:true
        });
    }
}
var breakPointCheck = function () {
    var currentWidth = $('.header').width();
    if (currentWidth != compareWidth) {
        compareWidth = currentWidth;
        setUpPage();
    }
}
setUpPage();
//    fixElement('.tabmenu')
$(window).resize(function () {
    breakPointCheck();
});
});

它们都是在 DOM 就绪函数中声明的,这给了它们一个local的作用域。然后,无法在该函数之外看到这些函数,并且每个 DOM 就绪函数都与其他函数分开。

您需要将它们声明为全局函数(使用全局变量):

例如

// Global scope
var mobileMenu;
$.noConflict();
jQuery(document).ready(function ($) {
     // Aside local function to global var
     mobileMenu = function(...

另一种方法是在 DOM 就绪处理程序外部声明函数,并确保仅从 DOM 就绪处理程序中的代码调用它们。显示的大多数函数不需要在 DOM 就绪处理程序中,因为它们只是声明,此时不会运行:

例如

$.noConflict();
//Declare global functions
var mobileMenu = function (menuParent, prevSibling, menuIdentifier) {
    if ($('#mobileMenu').length == 0) {
        var $select = $('<div>', {
            'class': 'mobile-menu',
            ...snip...
 });
 jQuery(document).ready(function ($) {
      // Use global functions
      mobileMenu(...);
 });

Use jQuery.getScript()

在共享函数脚本中,删除jQuery(document).ready(function () {...})包装器。

在特定于站点的文档中,使用 $.getScript() 加载共享文件,并将特定于站点的函数放在共享脚本成功加载后运行的回调中:

jQuery(document).ready(function() {
    $.getScript('/url/to/functionScript.js', function () {
        // Site specific functions
    });
});