前端如何实现异步加载

1. 动态创建html

所谓动态创建html, 无非按照你的配置动态创建节点, 然后添加到页面中

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
</body>
<script>
    var component = {
        config: {
            el: 'app',
            content: '<h1>hello world</h1>'
        },
        render: function() {
            var app = document.getElementById(this.config.el);
            if(!app) {
                throw 'you need careate a bootstrap dom which id property value is app';
                return;
            }
            app.innerHTML = this.config.content;
        }
    }
    component.render();
</script>
</html>

在上面的代码中:第一步先写一个配置对象, 它包括了需要动态创建的内容以及创建的方法。第一步调用对象中的方法。

2. 动态加载JS文件
现在需要将负责创建html的JS文件分离出去, 并且动态的引入到入口文件index.html中

// component.js
var component = {
    config: {
        el: 'app',
        content: '<h1>hello world</h1>'
    },
    render: function() {
        var app = document.getElementById(this.config.el);
        if(!app) {
            throw 'you need careate a bootstrap dom which id property value is app';
            return;
        }
        app.innerHTML = this.config.content;
    }
}
component.render();
// index.html
<!
doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="app"></div> </body> <script> //假设这里是异步的逻辑代码 setTimeout(function(){ var needLoad = 'component'; var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); //or srcipt.type = 'text/javascript'; script.src = needLoad + '.js'; document.body.appendChild(script); }, 1000); </script> </html>

3. 需要判断什么时候需要加载对应的js文件, 有时间再写

在浏览器notwork中, component.js被动态的加载, 页面变化但是浏览器并没有刷新。

整个过程你发现其实不是太难, 理解异步加载就是通过动态创建方式是关键。

其实可以得出一个结论:网页上的任何资源都可以异步加载(在需要的时候加载)

posted on 2017-04-22 19:26  码先生  阅读(1934)  评论(0编辑  收藏  举报