在外部javascript文件之前加载HTML

时间:2018-01-31 11:05:41

标签: javascript html

我想在外部javascript文件执行之前完全加载我的HTML。 当我加载我的index.html时,javascript会执行,并且在看到我的HTML内容之前会弹出一个警告框。如何首先加载HTML内容然后弹出窗口?



    var todos = ["Eat dinner"];
    var input = prompt("What would you like to do?");
    
    while(input !== "quit") {
        if(input === "list") {
            console.log(todos);
        }
        else if(input === "new") {
            // ask for a new ToDo
            var newTodo = prompt("Enter a new ToDo item");
            // add to ToDo's array
            todos.push(newTodo);
        }
        input = prompt("What would you like to do?");
    }
    console.log("Ok, you quit the app! :/");

<!DOCTYPE html>

<html lang="sv-se">
    <head>
        <meta charset="utf-8">
        <title>1.0 Javascript-kod</title>
        <link rel="stylesheet" href="assets/css/main.css">
        <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    </head>
    
    <body>
        <h1>ToDo List</h1>
        <ul>
            <li>"new" - Add a new ToDo item</li>
            <li>"list" - View all my ToDo items</li>
            <li>"quit" - Quit App</li>
        </ul>

        <!-- <script src="assets/js/script.js" type="text/javascript"></script> -->
        <script src="assets/js/todo.js" type="text/javascript"></script>
    </body>
</html>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

使用

(function()(
    alert("DOM loaded succesfully");
    var todos = ["Eat dinner"];
    var input = prompt("What would you like to do?");

    while(input !== "quit") {
    if(input === "list") {
        console.log(todos);
    }
    else if(input === "new") {
        // ask for a new ToDo
        var newTodo = prompt("Enter a new ToDo item");
        // add to ToDo's array
        todos.push(newTodo);
    }
    input = prompt("What would you like to do?");
  }
  console.log("Ok, you quit the app! :/");
))();

检查DOM的纯javascript事项已成功加载(function(){})();

答案 1 :(得分:0)

如果你想使用jQuery,你可以把你的代码放在

$(document).ready(function(){
 //HERE SHOULD BE YOUR CODE
});

答案 2 :(得分:0)

在事件处理程序中执行代码,而不是在解析时执行:

window.addEventListener("load", function(event){
    /* your code goes here */
});

但请记住,它可能会等待图像等加载。如果您需要在DOM树完全加载时执行某些操作,但其他所有内容尚未完成,请坚持将脚本放在</body>之前。尽管DOM解析在技术上还没有完成,但它仍然不会在那一刻向树中添加任何东西。