Home  >  Q&A  >  body text

javascript - jquery jsonp principle: js tag dynamically generated position problem

The principle of

jquery jsonp is to use the src attribute in the script tag to solve the cross-domain problems encountered in front-end and back-end data requests. One thing I don’t understand is that jquery dynamically generates The script tag is appended to the head tag, which is the head of the document; generally our callback function is in body, the function is declared first and then used, without declaration Why can we get the data passed from the background even if we call it directly?

The following is a test I did:

//同源策略下有两个文件:a.html和b.js.
//a.html中的内容为:


//<script type="text/javascript" src="b.js"></script>

function test(val){
    console.log(val)
}

//<script type="text/javascript" src="b.js"></script>


//b.js的内容为:
test(10)

If this string of code is placed below the declared test function, the number 10 will be printed. If it is placed above the test function, an error will be reported

ReferenceError: test is not defined

Comparing the implementation of jquery, I don’t quite understand why the dynamically generated js will be executed if it is called before the declared function?

迷茫迷茫2603 days ago749

reply all(4)I'll reply

  • ringa_lee

    ringa_lee2017-05-19 10:35:18

    //同源策略下有两个文件:a.html和b.js.
    //a.html中的内容为:
    
    
    //<script type="text/javascript" src="b.js"></script>
    
    function test(val){
        console.log(val)
    }
    
    //<script type="text/javascript" src="b.js"></script>
    
    
    //b.js的内容为:
    test(10)

    如果是直接链入的src的话,浏览器解析是从上往下解析的,就会先取回b.js里面的值,a.js的函数还未加载进入页面,此时是没有test()这个函数的,所以会报错

    但是发ajax请求是等页面完成后再去请求的,即等是先声明好了一个回调函数再去 创建一个script去请求,所以此时的script放的位置在哪里并不会影响最后的结果。

    Reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:35:18

    因为你忽略了异步的问题,从执行顺序来说,当从服务器发回的script标签加载完成之后,你本地的callback函数肯定是已经定义完成的,因此能够的调到相应的方法。
    简单来说就是:
    jsonp=定义本地回调函数=>加载script标签=>运行所加载script标签内容。

    Reply
    0
  • 天蓬老师

    天蓬老师2017-05-19 10:35:18

    jsonp 说白了就是个约定:
    '我们俩隔太远了, 够不着, 你东西要怎么给我?'
    '要不我往你那扔吧, 你能接住么?'
    '可以, 我有个篮子(callback), 在你1点钟方向(callbackName), 你往那扔'
    至于篮子存不存在, 位置摆的对不对, 并不影响你们的约定

    Reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:35:18

    jsonp引入的js加载位置是在执行jsonp获取js的语句的位置。至于放的位置只是一个形式罢了。

    Reply
    0
  • CancelReply