简体   繁体   中英

How to load an external JS library that has code between <script> tags using jQuery

The original code I have is

<script type="text/javascript" src="http://platform.linkedin.com/in.js">
    api_key: qwerty
</script>

I want to make this code happen using jQuery after something has been triggered. Something like this

jQuery.getScript('http://platform.linkedin.com/in.js');

The problem is that I am not sure what the api_key part does, I've never seen the combination of a request to external lib and code between script tags. Is there a way to imitate that with jQuery? And also - what does that line do? :)

Thanks!

It's not exactly the answer to the question I originally posted, which is more abstract. But in case someone stumbles on this question in connection to linkedin, here's the way to load their framework asynchronously.

jQuery.getScript("http://platform.linkedin.com/in.js?async=true", function success() {
    IN.init({
        api_key: "qwerty"
    });
});

I did some digging through what happens when you load the script, and found that in.js parses the contents of the tag whose src is itself and uses them to build a new script tag to append to the head.

Based on your post, it appended

<script src="https://www.linkedin.com/uas/js/userspace?v=0.0.2000-RC1.20888-1402&amp;apiKey=qwerty&amp;"></script>

to the head. userspace.js obviously rejected the api key, but because this is a proprietary method of loading data, I can't predict how it'll work if and when you try to turn that into an ajax call.

Update: According to the script tag standard , "If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI." This allows LinkedIn to get away with putting invalid Javascript inside the script tag, knowing it'll never get evaluated by the browser.

This should work correctly on jQuery mobile site.

<script type="IN/Apply" data-companyname="XXX" data-jobtitle="XXX" data-joblocation="XXX" data-email="XXX@XXX.XXX">
</script>
<script type="text/javascript">
$(function() {
    if(typeof(IN)=="undefined"){
        $.getScript("//platform.linkedin.com/in.js?async=true", function success() {
            IN.init({api_key: "XXX"});
        });
    }
    else{
        IN.parse();
    }
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM