search

Home  >  Q&A  >  body text

javascript - How to load a js file before opening the website?

And after the website is loaded and opened normally, the code for loading js will not be displayed in the web page code. Can this be done? ? ? Solve

曾经蜡笔没有小新曾经蜡笔没有小新2736 days ago666

reply all(4)I'll reply

  • 大家讲道理

    大家讲道理2017-05-31 10:36:00

    I don’t know how the questioner defines it before the website is opened?

    If you just want the web page to load js files earlier, you can put the script reference in the head tag.
    However, the question also requires that the web page code does not display the js after opening. This is how I understand it. In this case, there are two main steps:

    1. Write an inline js code in the head tag. The main function of the code is to introduce the js file and follow-up actions

    2. The so-called follow-up action is to trigger the loading event after introducing the file to remove the introduction of the file from the document dom

    I will simply list a demo:

    First prepare the page t.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>waterfall</title>
        <script type="text/javascript">
            (function(){
                // 动态加载script
                var script = document.createElement('script');
                var head = document.getElementsByTagName('head')[0];
                // console.log(head);
                // 脚本加载完就移除
                script.onload = function(){
                    console.log('loaded script ready to remove');
                    head.removeChild(script);
                };
                script.src = './t.js';
                console.log('load script');
                // 将script放到head里
                head.appendChild(script);
            })();
        </script>
    </head>
    <body>
        <p id="wrap" class="wrap"></p>
    </body>
    </html>

    Introduced js: t.js

    (function(){
        console.log('hello i am t');
    })()

    I wonder if this is the main effect of the question?

    reply
    0
  • ringa_lee

    ringa_lee2017-05-31 10:36:00

    If you want to improve the loading speed, you can use cache to load js in advance. I have never encountered this before

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-31 10:36:00

    Use a web server (such as nginx) to insert content into the page?
    Then this js is also monitoring whether the page has been loaded, and deletes itself after loading.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-31 10:36:00

    Try putting the actual web page in the iframe and js outside the iframe?

    reply
    0
  • Cancelreply