简体   繁体   中英

Moving inline Javascript to external .js file

I have some inline Javascript in my <body> that I'm trying to export to a .js file. I know that normally you would just copy/paste it over, sometimes including it in a document ready function, but something about this one is different. I'm not super fluent in JS and the code wasn't written by me (but was provided free online).

This is how the code is in my file. If you need any more info just ask!

<body>
    <script>
    (function (window, document) {
    var menu = document.getElementById('menu')
        , WINDOW_CHANGE_EVENT = ('onorientationchange' in window) ? 'orientationchange' : 'resize';

    function toggleHorizontal() {
    [].forEach.call(document.getElementById('menu').querySelectorAll('.custom-can-transform'), function (el) {
            el.classList.toggle('pure-menu-horizontal');
        });
    };

    function toggleMenu() {
        // set timeout so that the panel has a chance to roll up
        // before the menu switches states
        if (menu.classList.contains('open')) {
            setTimeout(toggleHorizontal, 500);
        }
        else {
            toggleHorizontal();
        }
        menu.classList.toggle('open');
        document.getElementById('toggle').classList.toggle('x');
    };

    function closeMenu() {
        if (menu.classList.contains('open')) {
            toggleMenu();
        }
    }
    document.getElementById('toggle').addEventListener('click', function (e) {
        toggleMenu();
        e.preventDefault();
    });
    window.addEventListener(WINDOW_CHANGE_EVENT, closeMenu);
    })(this, this.document);

    </script>
</body>

UPDATE: I was able to wrap the script in a scope ( foo = function() {} ) and get it to work externally by adding window.onload = function to the HTML page. This was suggested by @marmeladze and worked.

如@marmeladze所建议,我能够将脚本包装在一个范围( foo = function() {} )中,并通过将window.onload = function添加到HTML页面来使其在外部工作。

So what is the real problem to export it in an external js file?

As always i would copy and past code in a new js. Link it to HTML page and write functions that i need as attribute of HTML's tag (ex. "onload=functioname();" in body's tag). As marmeladze said you can wrap all in an unique scope so you can call it in body.

Maybe you are doing it so if you maybe can explain better your problem would be great.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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