最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

web applications - how to structure javascript files? - Stack Overflow

programmeradmin5浏览0评论

I have

  • base.html
  • pageA.html
  • pageB.html
  • pageA.js
  • pageB.js

    1. pageA.js has code for pageA.html, pageB.js has code for pageB.html.
    2. both pageA.js and pageB.js uses jQuery.

currently I am including all of the scripts in base.html, like so:

<html>
  <body>
    <div id="contents">
      <!-- pageA.html / pageB.html es here -->
    </div>
    <script src="js/jquery.js"></script>
    <script src="js/pageA.js"></script>
    <script src="js/pageB.js"></script>
  </body>
</html>

I'd like to load pageA.js only for pageA.html and pageB.js for pageB.html, as the code in each file is not needed in the other page.

I've looked into requires.js library, but I'm not sure yet if it is the right solution for my problem. What are the best practices for structuring javascript files in this type of situation?

I have

  • base.html
  • pageA.html
  • pageB.html
  • pageA.js
  • pageB.js

    1. pageA.js has code for pageA.html, pageB.js has code for pageB.html.
    2. both pageA.js and pageB.js uses jQuery.

currently I am including all of the scripts in base.html, like so:

<html>
  <body>
    <div id="contents">
      <!-- pageA.html / pageB.html es here -->
    </div>
    <script src="js/jquery.js"></script>
    <script src="js/pageA.js"></script>
    <script src="js/pageB.js"></script>
  </body>
</html>

I'd like to load pageA.js only for pageA.html and pageB.js for pageB.html, as the code in each file is not needed in the other page.

I've looked into requires.js library, but I'm not sure yet if it is the right solution for my problem. What are the best practices for structuring javascript files in this type of situation?

Share Improve this question edited Apr 22, 2013 at 3:38 Yeonho asked Apr 22, 2013 at 3:29 YeonhoYeonho 3,6235 gold badges41 silver badges62 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 1

I think that the best you can do is add the <script src="js/pageX.js"></script> in the end of the pageX.html IF this page is loaded dynamically. If the page isn't loaded dynamically, it may load before jquery.js and break you javascript.

Or you can read the current URL and load the correct script based on this info, like this:

var scriptPath;
var currentPage = window.location.pathname;

if (currentPage == "pageA.html")
{
    scriptPath = "pageA.js";
}
else if (currentPage == "pageB.html")
{
    scriptPath = "pageB.js";
}

var scriptElement = document.createElement("script");
scriptElement.setAttribute("type", "text/javascript");
scriptElement.setAttribute("src", scriptPath);

document.getElementsByTagName("head")[0].appendChild(scriptElement);

Do you have JavaScript to load in the contents of each html file? If so, and you have JavaScript code to run once each file is loaded you can call the required setup functions inside the load function like this:

base.html

<html>
    <head>
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/pageA.js"></script>
        <script type="text/javascript" src="js/pageB.js"></script>
        <script type="text/javascript">
            $(document).ready(function()
            {
                $('#loadPageA').on('click', function()
                {
                    $('#contents').load('pageA.html', function()
                    {
                        setupPageA(); // defined in pageA.js
                    });
                });

                $('#loadPageB').on('click', function()
                {
                    $('#contents').load('pageB.html', function()
                    {
                        setupPageB(); // defined in pageB.js
                    });
                });
            });
        </script>
    </head>
    <body>
        <div id="contents"></div>
        <a id="loadPageA">Load Page A</a>
        <a id="loadPageB">Load Page B</a>
    </body>
<html>

Or, you if you just want to run pageA.js when pageA.html is loaded in you can just include the pageA.js script element in page pageA.html itself, like this:

pageA.html:

<div id="pageAContent">Page A</div>
<script type="text/javascript src="js/pageA.js"></script>

pageB.html:

<div id="pageBContent">Page B</div>
<script type="text/javascript src="js/pageB.js"></script>

base.html:

<html>
    <head>
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function()
            {
                $('#loadPageA').on('click', function()
                {
                    $('#contents').load('pageA.html');
                });

                $('#loadPageB').on('click', function()
                {
                    $('#contents').load('pageB.html');
                });
            });
        </script>
    </head>
    <body>
        <div id="contents"></div>
        <a id="loadPageA">Load Page A</a>
        <a id="loadPageB">Load Page B</a>
    </body>
<html>

The dynamic script src solution:

base.html:

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis./ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript">
            function loadScript(script)
            {
                // Modify the existing script tag
                if($('#dynamicScriptTag').length != 0)
                {
                    $('#dynamicScriptTag').attr('src', script);
                }
                else // Create script tag
                {
                    $('<script>').attr('type', 'text/javascript')
                                 .attr('src', script)
                                 .attr('id', 'dynamicScriptTag')
                                 .appendTo('head');
                }
            }

            $(document).ready(function()
            {
                $('#loadPageA').on('click', function(event)
                {
                    event.preventDefault();
                    $('#contents').load('pageA.html', function()
                    {
                        loadScript('js/scriptA.js');
                        testScriptB(); // test if we can still call a function in scriptB.js
                    });
                });

                $('#loadPageB').on('click', function(event)
                {
                    event.preventDefault();
                    $('#contents').load('pageB.html', function()
                    {
                        loadScript('js/scriptB.js')
                        testScriptA(); // test if we can still call a function in scriptA.js
                    });
                });
            });
        </script>
    </head>
    <body>
        <div id="contents"></div>
        <a id="loadPageA" href="#">Load Page A</a>
        <a id="loadPageB" href="#">Load Page B</a>
    </body>
</html>

pageA.html:

<div id="pageAContents">Page A</div>

pageB.html:

<div id="pageBContents">Page B</div>

js/scriptA.js:

console.log($('#pageAContents').text());
function testScriptA(){ console.log('Can still call testScriptA!'); }

js/scriptB.js:

console.log($('#pageBContents').text());
function testScriptB(){ console.log('Can still call testScriptB!'); }

I ended up using Jinja(a template engine) to place the javascript files like following:

base.html

<html>
  <body>
    <div id="contents">
      {% block contents %}
      {% endblock %}
    </div>
    <script src="js/jquery.js"></script>
      {% block scripts %}      
      {% endblock %}       
  </body>
</html>

pageA.html

{% block contents %}
   ..page A contents..
{% endblock %}
{% block scripts %}
<script src="js/pageA.js"></script>
{% endblock %}

If you are using a template engine, it could be a viable solution.

发布评论

评论列表(0)

  1. 暂无评论