简体   繁体   English

使用ASP.NET从第二个文件调用JS函数

[英]Calling a JS function from a second file using ASP.NET

I have an ASP.NET web application that makes use of a large Javascript file to enable front-end functionality. 我有一个ASP.NET Web应用程序,它使用大型Javascript文件来启用前端功能。 The issue is that since this web application is growing in size the Javascript file is growing in size along with it. 问题是,由于此Web应用程序的大小不断增长,因此Javascript文件的大小也在不断增加。

I want to remove some of my larger functions out of my main javascript file site.js and instead contain them inside a second file. 我想从我的主要javascript文件site.js删除一些较大的函数,而是将它们包含在第二个文件中。 My aim is to declutter the main JS file and increase readability etc. 我的目标是整理主要的JS文件并提高可读性等。

If this were a normal web application I'm sure I'd be able to use JQuery to achieve this through use of the .getScript() however I've tried using this function to pull in a separate script with a simple alert function and I get a reference error saying that my alert function is undefined. 如果这是一个普通的Web应用程序,我确信我可以通过使用.getScript()来使用JQuery来实现这一点。但是我尝试使用此函数来引入一个带有简单警报功能的单独脚本,我收到一个引用错误,说我的警报功能未定义。 I have included both scripts within my ASP.NET _Layout view, but still it doesn't work. 我在ASP.NET _Layout视图中包含了这两个脚本,但它仍然不起作用。

Below is what I am doing currently, what do I need to do to be able to call a JS function held inside another file from site.js? 下面是我目前正在做的事情,我需要做些什么来调用site.js中另一个文件中保存的JS函数?

site.js site.js

$(function() {

    $(document).ready(function() {
        $.getScript("../site2.js");

        sendAlert();
    });

    //... other js

});

site2.js site2.js

$(function() {

    function sendAlert() {
        alert("site2 file");
    }

});

_Layout _布局

<!DOCTYPE html>
<html>
<head>
    <script src="~/js/site2.js"></script>
    <script src="~/js/site.js"></script>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css" integrity="sha384-88btmYK8qOHy4Z2XuhkWZjUOHICKYe1eSDMwaDGOAy802OCu6PD6mwqY5OwnfGwp" crossorigin="anonymous">
    <script defer src="https://use.fontawesome.com/releases/v5.1.0/js/all.js" integrity="sha384-3LK/3kTpDE/Pkp8gTNp2gR/2gOiwQ6QaO7Td0zV76UFJVhqLl4Vl3KL1We6q6wR9" crossorigin="anonymous"></script>
</head>
<body>

@RenderBody()


@RenderSection("Scripts", required: false)
</body>
</html>

I think that you can do this: 我认为你可以这样做:

$(function() {

    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "../site2.js");
    document.getElementsByTagName("head")[0].appendChild(script);

});

Cheers - Vinh 干杯 - 荣

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

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