What are the ways to terminate JS requests?
typecho
typecho 2017-06-28 09:28:55
0
3
1058

I encountered a similar problem during the interview. The general idea is that when loading the page, some js file resources will be loaded using script tags. If these resources are not requested back for a long time, how to manually terminate the request?

I know that Ajax requests have an abort method. I wonder if the interviewer wants to ask this, and is there any other way to terminate the request?

typecho
typecho

Following the voice in heart.

reply all(3)
我想大声告诉你

Thanks for the invitation.
Like @小Stream said, it’s timeout.

The rough implementation idea is as follows:

var sequence = ['foo', 'bar', 'baz', 'base', 'ball', 'hello', 'world', '100k more'],
    start = Date.now();

setTimeout(function _worker() {
    do {
       var element = sequence.shift();
       // do something with element
    } while( sequence.length && (Date.now() - start < 100) );

    if( sequence.length )
        setTimeout(_worker, 25);
}, 25);

In the above example, queue loading is performed at intervals of 25 milliseconds, and the loading time is within 100ms.

给我你的怀抱

What should be examined is the timeout of loading resources

typecho

The loading of

<script> is always synchronous (blocking) and cannot be affected by DOM operations. What the subject needs is asynchronous JS loading that is independent of page loading and rendering. There are many tools, here is an example of RequireJS:

HTML page:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<script src="//cdn.staticfile.org/require.js/2.1.15/require.min.js" data-main="test1"></script>
</head>
<body></body>
</html>

Save as test1.js:

require.config({
    paths: {
        'jquery': '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery',
        'underscore': '//cdn.bootcss.com/underscore.js/1.7.0/underscore'
    },    
    waitSeconds: 20
});
require(['jquery'], function (module) {
    console.log("jQuery " + $.fn.jquery + " successfully loaded. ");
}, function (err) {
    console.log("SHIT happened while loading jQuery! ");
});
require(['underscore'], function (module) {
    console.log(_.last([1, 2, 3, "Underscore.js successfully loaded. "]));
}, function (err) {
    console.log("SHIT happened while loading Underscore.js! ");
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template