本文介绍了为不同的页面加载不同的js文件或一起加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3页的网站。

这些javascript文件是不重复的,意味着第1页上需要的JS在第2页上不需要,而且我的过期头文件设置为1个月。



我仍然想知道加载这些文件的最佳方式,我应该为每个页面加载单独的文件还是将它们加载在一起?

解决方案

你应该单独加载它们......

但是,为了加快速度,你可以做一个技巧:如果您认为用户在页面上停留了一段时间(我不知道,至少5秒),您可以加载该页面的脚本,并在页面加载后远程添加其他页面。这样你就可以强制客户端的浏览器创建另一个的缓存副本 - 目前不需要--js文件,并且因为在dom对象建立之后它们被加载,所以它不会减慢你的页面渲染速度。
您必须添加一个addScript函数,并在文档加载完成后进行addScript调用。
对于第一个js(第一页),应该是这样的:

 
function addScript(jsUrl){
var s = document.createElement('script');
s.setAttribute('type','text / javascript');
s.setAttribute('src',jsUrl);
document.getElementsByTagName('body')[0] .appendChild(s);
}
window.onload = function(){
addScript('mySecondScript.js');
addScript('myThirdScript.js');


当您加载其他页面时,相应的js文件会立即加载,因为它是从浏览器的缓存中检索。


I have 3 pages of site.

These javascript files are non repeating, means the JS needed on page 1 is not needed on page 2 and I have expiry headers set 1 month.

Still I would like to know what will be best way to load these files, should I load separate file for each page or I load these all together?

解决方案

you should probably load them separately...
But, in order to speed things up you could do a trick : if you think that the user is staying for a bit (i donno, at least 5 sec) on your page, you could just load the script for that particular page and add the other ones remotely after the page loads. This way you force the client's browser to make a cache copy of your other - not needed at the moment - js files, and because they're being loaded after the dom object has been built, it doesn't slow your page rendering.
You will have to add an "addScript" function and make "addScript" calls when the document has finished loading. For the first js (for the first page) it should be something like :

function addScript(jsUrl){
    var s = document.createElement('script');
    s.setAttribute('type','text/javascript');
    s.setAttribute('src',jsUrl);
    document.getElementsByTagName('body')[0].appendChild(s);
}
window.onload = function(){
    addScript('mySecondScript.js');
    addScript('myThirdScript.js');
}

The beauty is that when you load one of the other pages, the corresponding js file is loaded instantly because it is retrieved from the browser's cache.

这篇关于为不同的页面加载不同的js文件或一起加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 15:50