Loading an external script after loading a page using jQuery

I'm a little confused how to do this, basically I have a page with a Facebook Share button inserted using JavaScript:

<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>

The problem is that it blocks the page loading in this part, how can I insert this tag after the page loads and still execute the script? I would like to do it unobtrusively, ideas?

+3
source share
5 answers

Use the jQuery getScript command inside $(document).ready. This will load the script after the page loads. Example:

$(document).ready(function() {
    $.getScript("http://static.ak.fbcdn.net/connect.php/js/FB.Share", function() {
        alert("Script loaded and executed.");
    });
});
+9
source

You can use jquery.getScripts to load it asynchronously.

+3
source

- :

$(document).ready(function() {
    var script = document.createElement( 'script' );
    script.src = "http://static.ak.fbcdn.net/connect.php/js/FB.Share";
    script.onload=optionallyDoSomethingWithTheScriptYouJustLoaded();//not needed
    var headID = document.getElementsByTagName("head")[0];         
    headID.appendChild(script);
 });
+3

script dom .

0
source

you can do something like:

$(function() {
  $.getScript('http://static.ak.fbcdn.net/connect.php/js/FB.Share', function() {
    //do nothing here
  });
});
0
source

Source: https://habr.com/ru/post/1789628/


All Articles