前端如何实现异步加载

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被动态的加载, 页面变化但是浏览器并没有刷新。

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

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

转载于:https://www.cnblogs.com/noper/p/6748874.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值