Ways to add javascript files dynamically in a page

后端 未结 9 1626
盖世英雄少女心
盖世英雄少女心 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:47

    I've seen what the scriptaculous loader does. What it does is that it goes through all script tags in the document to find the one that loaded itself, e.g:

    
    

    Then it parses the querystring used inside the src attribute and dynamically create additional script tags for each script file. At the same time it also parses the path of the base script (/path/to/single.js) and uses the same path to load dependency files (e.g. /path/to/first.js).

    You can create your own script loader like this. In vanilla javascript, you can use the following functions:

    • getElementsByTagName -- find all scripts
    • getAttribute -- find src/href/type attribute
    • createElement -- create a script element
    • appendChild -- append to head/body

    Anand Thangappan has posted a solution that uses these functions. If you're using a framework such as jQuery or MooTools then both provide their own implementations of dynamically loading JsvaScript.

    Finally, there is a server side solution for your problem. Look at minify -- Combines and minifies multiple CSS or JavaScript files into a single download.

提交回复
热议问题