Ways to add javascript files dynamically in a page

后端 未结 9 1640
盖世英雄少女心
盖世英雄少女心 2020-11-28 09:16

I have seen Scriptaculous.js file to include its required javascript files dynamically. Is there any better approach to include javascript dynamically.

For example,

9条回答
  •  清歌不尽
    2020-11-28 09:50

    Following the advice of Salaman A's comments, I found how Google does it now with Analytics: https://developers.google.com/analytics/devguides/collection/gajs/asyncTracking

    And here is a more generic version of the same code:

    (function() {
        var s = document.createElement('script'); // Create a script element
        s.type = "text/javascript";               // optional in html5
        s.async = true;                           // asynchronous? true/false
        s.src = "//example.com/your_script.js"; 
        var fs = document.getElementsByTagName('script')[0];  // Get the first script
        fs.parentNode.insertBefore(s, fs);
    })();
    

提交回复
热议问题