A method instance of Web page delay loading JS file

Source: Internet
Author: User
Tags abs bind eval gety script tag setinterval

3 ways to delay loading JS files with Web pages


1. Delay Loading JS Code

The code is as follows:

<script type= "Text/javascript" src= "id=" my "></script>

<script type= "Text/javascript" >

settimeout ("document.getElementById"). src= ' http://www.geilijz.com + js.js '; ", 3000);//delay 3 seconds

</script>

This way by delaying loading JS code, to allow more time to load the page!

2, JS final load scheme a

Insert the following code where you want to insert JS:

<span id= "L4ever" >LOADING...</span>

Of course, that loading ... You can switch to your favorite small picture. It looks like an Ajax effect.

Then insert the following code at the bottom of the page:

<span id= "Ad_l4ever" > Your JS code is here!</span >

<script>L4EVER.innerHTML=AD_L4EVER.innerHTML; Ad_l4ever.innerhtml= "";</script>

3, let JS final load scheme two

This involves the loading sequence of the page, such as the introduction of external JS script file, if placed in the head of the HTML, the page before loading the JS script will be loaded into the page, and into the body, will be in accordance with the page from the loading sequence of the collapse to run.

JavaScript code ~ ~ So we can put JS outside the introduction of the file to the bottom of the page, to let JS finally introduced, so as to speed up the page load.


the method of 7 kinds of JS delay load Execution

Lazy-load JavaScript, which is loaded after the page has finished loading, is also called on demand (on demand), usually with several methods:
1. DOM
Head Append script Tag

Window.onload = function () {
settimeout (function () {

Reference to var head = document.getElementsByTagName (' head ') [0];

A new CSS
var css = document.createelement (' link ');
Css.type = "Text/css";
Css.rel = "stylesheet";
Css.href = "New.css";

A new JS
var js = document.createelement ("script");
Js.type = "Text/javascript";
JS.SRC = "New.js";

Preload JS and CSS
Head.appendchild (CSS);
Head.appendchild (JS);

Preload image
New Image (). src = "new.png";

}, 1000);
};

2. document.write

<script language= "javascript" type= "Text/javascript" >
function include (script_filename) {
document.write (' < ' + ' script ');
document.write (' language= "JavaScript");
document.write (' type= "text/javascript");
document.write (' src= "' + script_filename + '" > ');
document.write (' </' + ' script ' + ' > ');
}

var which_script = ' 1.js ';
Include (Which_script);
</script>

3. Iframe
Similar to the first one, but the script tag is placed in the document of the IFRAME.

Window.onload = function () {
settimeout (function () {

Create new IFRAME
var iframe = document.createelement (' iframe ');
Iframe.setattribute ("width", "0");
Iframe.setattribute ("height", "0");
Iframe.setattribute ("frameborder", "0");
Iframe.setattribute ("name", "preload");
Iframe.id = "preload";
IFRAME.SRC = "About:blank";
Document.body.appendChild (IFRAME);

Gymnastics to get reference to the IFRAME document
iframe = document.all? Document.all.preload.contentWindow:window.frames.preload;
var doc = iframe.document;
Doc.open (); Doc.writeln ("
Create CSS
var css = doc.createelement (' link ');
Css.type = "Text/css";
Css.rel = "stylesheet";
Css.href = "New.css";

Create JS
var js = doc.createelement ("script");
Js.type = "Text/javascript";
JS.SRC = "New.js";

Preload CSS and JS
Doc.body.appendChild (CSS);
Doc.body.appendChild (JS);

Preload IMG
New Image (). src = "new.png";

}, 1000);
};

4. Iframe static page
Just put what needs to be loaded into another page

Window.onload = function () {
settimeout (function () {

Create a new frame and point to the URL of the static
Page that has all components to preload
var iframe = document.createelement (' iframe ');
Iframe.setattribute ("width", "0");
Iframe.setattribute ("height", "0");
Iframe.setattribute ("frameborder", "0");
IFRAME.SRC = "preloader.html";
Document.body.appendChild (IFRAME);

}, 1000);
};

5. Ajax Eval
Download the code with Ajax and execute it with eval

6. Ajax Injection
Download the code with AJAX, create an empty script tag, set the Text property to download the code

7. Async property (disadvantage is that the order of loading cannot be controlled)
<script src= "" async= "true"/>



JS delay loading mechanism function (Lazyload)

It should have been discovered recently that many of my blogs use deferred loading techniques. This delay load (lazyload) I first heard that it was not long ago, it was in someone else's blog to see the introduction of a jquery based image delay loading plug-in. I am very interested in this, in fact, many sites have also applied this technology, especially large web sites, can effectively reduce server pressure.

I thought the technology was very mysterious, it should be more difficult to achieve, and online also did not find relevant articles or introductions. But when I really decided to do it, I found it was really simple and the principle was easy to understand.

Lazyload, to put it simply, is to start the relevant function when the browser scrolls to a certain position, to implement the loading of the page elements or the execution of some actions. Browser scrolling position detection, through a timer to cycle detection, by comparing a moment page target node position and browser scroll bar height to determine the need to perform functions. I have written this method as a class, and my own blog is using my method.

(The following code is purely own small Taker, if there are imperfect places to point out)

function Lazyload (func, obj) {//obj target node objects, func the functions to be triggered
This.func = func;
This.obj = obj;
this.it = setinterval (function () {//2s Check once
This.checkscroll ();
}.bind (this),//bind is setinterval bound Lazyload object, otherwise this will point to the Window object
}

Function.prototype.bind = function (obj) {//Object binding
var __method = this;
return function () {
return __method.apply (obj, arguments);
};
}

Lazyload.prototype.checkScroll = function () {
var scrolly = Document.body.scrollTop | | Document.documentElement.scrollTop | | Window.pageyoffset | | 0,//page scroll bar height
Seey = window.innerheight| | document.documentelement.clientheight,//Browser Visual Area height
func = This.func;
if (Math.Abs (This.gety ()-scrolly) < Seey) {//when the target node enters the viewable area, the page scroll bar height minus the node distance from the top of the page is less than the browser visual height
Clearinterval (this.it);//Clear Timer
return func ();
}
}


Lazyload.prototype.gety=function () {//target node height from top of page
var obj=this.obj;

TP = Obj.offsettop;

if (obj.offsetparent) while (obj = obj.offsetparent) tp + = Obj.offsettop;
return TP;
}


Some of the explanations for the code are in the comments. How to use it?


Use this method to create a new method for a class object through new. parameter func is the function to trigger, and obj is a node object on the page that triggers the Func function when this obj node enters the viewable area (the browser scrolls here). For example, if you want to implement a pop-up alert (' Yes ') when the browser scrolls to a node (b) with the ID "test" on the page, you can do so

function A () {alert (' yes ');} The function to start
var B=document.getelementbyid (' tests ');/get page node
New Lazyload (A,B);//create object execution with new keyword

The above is my own lazyload all the code and implementation of the way. Of course, I believe there is some improvement in it.

To add something else:

The time set for timing detection in my code is 2s, which means to compare it every two seconds. If your browser is dragging too fast and the target node is quickly flashing, it is possible that the Checkscroll function is not executed at this time, so it will not trigger the action. You can change the time to a smaller value (on line 6th), such as 500ms, to avoid the problems caused by most of the quick drag. Of course, I think there is no need, if someone quickly drag the scroll bar, indicating that he is going to browse the bottom of the page, it is not necessary to load his fast-dragging nodes, so 2s i think is a very reasonable value.

Another problem is that my code only triggers the node actions that appear in the viewable area, and if you want to implement all the nodes in the section above the current page, you can remove the Math.Abs from the 20th line of the code. If you want to implement a trigger function when scrolling to a certain height from the target node, you can change the seey of 20 rows to seey+200 (200 is the set height of the distance).

About a specific implementation of lazyload, but also take the picture of delay loading. You can change the address of the picture to a default small picture (this can be in the background with PHP directly modify the output, can also be implemented with JS, the real picture address to the Alt attribute of the picture (you can also specify a custom attribute), and then bind to each picture new lazyload, The action function to trigger is to assign the value in ALT to SRC. In this way, the realization of the picture of the lazyload (you can eliminate jquery, the elimination of jquery Lazyload Plug-ins, but also eliminate the 100来 K of the JS file). If you combine Ajax technology, then you can implement the same as my blog module delay loading.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.