Skip to content

Instantly share code, notes, and snippets.

@sofish
Created July 3, 2012 03:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sofish/3037397 to your computer and use it in GitHub Desktop.
Save sofish/3037397 to your computer and use it in GitHub Desktop.
seajs send 404 request
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Loader</title>
<link href="http://typo.sofish.de/typo.css" rel="stylesheet" />
<style type="text/css">
code{padding:0 2px;border:1px solid #eee;background:#f7f7f7;border-radius:3px;}
</style>
<script src="http://test.com:8080/static/??sea/sea.js,modules/jquery-1.7.2.min.js"></script>
</head>
<body class="typo" style="padding:20px 60px;">
<h3>#测试异步加载</h3>
<blockquote id="test">
我现在的位置是:<span id="geo">Loading...</span>
</blockquote>
<h3>#开发原则</h3>
<ul>
<li>默认框架 module 不应该用 seajs 来加载
<p>sea 使用的是传统的 script insertion,默认框架一来永远都是不动的,二来总是需要最先载入的,如果使用 <code>seajs.use()</code> 加载则会产生 insertion 这个过程,反而让页面更慢。</p>
</li>
</ul>
<h3>#注意点</h3>
<ul>
<li>所有 module 都需要经过 <code>seajs.define()</code> 预先定义
<p>可以参考现有这个 <a href="http://test.com:8080/static/modules/jquery-1.7.2.min.js">jQuery-1.7.2.min.js</a>。
</li>
<li>版本可以利用 <code>seajs.config()</code> 中配置 <code>alias</code> 来实现别名。不建议直接删除版本号
</ul>
<script>
seajs.config({
base: 'http://test.com:8080/static/modules'
});
seajs.use(['jquery', 'geolocation'], function($, geo){
geo(function(coords){
$('#geo').html(coords.latitude + ', ' + coords.longitude);
}, function(err){
alert('error occurred: ' + err);
})
})
</script>
</body>
</html>
@lifesinger
Copy link

@sofish

有几点想探讨下:

  1. jquery 等框架文件的同步引入。我推荐还是异步引入,目前支付宝是这样用的:

页头:

<script src="https://a.alipayobjects.com/static/arale/seajs/1.2.0/sea.js,plugin-combo.js" id="seajsnode"></script>
<script>
// 全部配置,除了 jquery 还可以有其他
seajs.config({
  alias: {
    '$': 'jquery/1.7.2/jquery'
  }
})

// 异步独立加载 jquery
seajs.use('jquery')
</script>

页面中:

seajs.use(['$', 'xx'], function($, xx) {
   // biz code
})

异步加载 jquery 等类库文件有一个好处:用户第一次打开页面时,jquery.js 的加载不是同步阻塞的,能比较明显的提高无缓存用户的页面打开速度。

无缓存用户,根据在淘宝时的统计,有 20-30% 多,挺大的占比,还是得考虑。这批用户往往是新用户,页面速度是留住新用户的因素之一,不可小觑。

至于异步插入 script 导致的页面 reflow,个人觉得可以忽略。而且,seajs.use('jquery') 是放在页面头部的,插入时页面还没开始渲染,不会增加 reflow

一楼提到的重复发请求的问题,是 combo 导致的。目前已修复,可以到 https://github.com/seajs/seajs/tree/master/dist 下载覆盖下就好。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment