Trying to load an API and a JS file dynamically

后端 未结 3 562
别跟我提以往
别跟我提以往 2021-02-09 02:46

I am trying to load Skyscanner API dynamically but it doesn\'t seem to work. I tried every possible way I could think of and all it happens the content disappears.

I tri

3条回答
  •  梦如初夏
    2021-02-09 02:56

    For problematic cases like this, you can just overwrite document.write. Hacky as hell, but it works and you get to decide where all the content goes. See eg. this blogpost by John Resig. This ignores IE, but with a bit of work the trick works in IE as well, see eg. this blogpost.

    So, I'd suggest overwriting document.write with your own function, batch up the output where necessary, and put it where you like (eg. in a div at the bottom of your '). That should prevent the script from nuking your page's content.

    Edit: OK, so I had/took some time to look into this script. For future reference, use something like http://jsbeautifier.org/ to investigate third-party scripts. Much easier to read that way. Fortunately, there is barely any obfuscation/minification at all, and so you have a supplement for their API documentation (which I was unable to find, by the way -- I only found 'code wizards', which I had no interest in).

    Here's an almost-working example: http://jsfiddle.net/a8q2s/1/

    Here's the steps I took:

    1. override document.write. This needs to happen before you load the initial script. Your replacement function should append their string of code into the DOM. Don't call the old document.write, that'll just get you errors and won't do what you want anyway. In this case you're lucky because all the content is in a single document.write call (check the source of the initial script). If this weren't the case, you'd have to batch everything up until the HTML they'd given you was valid and/or you were sure there was nothing else coming.
    2. load the initial script on the button click with jQuery's $.getScript or equivalent. Pass a callback function (I used a named function reference for clarity, but you can inline it if you prefer).
    3. Tell Skyscanner to load the module.

    Edit #2: Hah, they have an API (skyscanner.loadAndWait) for getting a callback once their script has loaded. Using that works:

    http://jsfiddle.net/a8q2s/3/

    (note: this still seems to use a timeout loop internally)

提交回复
热议问题