开发者

How to insert a resource in a .js file?

开发者 https://www.devze.com 2023-04-03 11:20 出处:网络
I have my scripts.js file. If I\'d like to insert an external resoruce (like the swfobject.js library from yout开发者_高级运维ube) inside this file how can I do it?

I have my scripts.js file.

If I'd like to insert an external resoruce (like the swfobject.js library from yout开发者_高级运维ube) inside this file how can I do it?

Like :

<script type="text/javascript" src="swfobject.js"></script>   

Is it possible? Maybe with less code with jQuery...


You can use the getscript api of jQuery

$.getScript('swfobject.js', function(data, textStatus){ })

jQuery.getscript()


Please see:

http://jqfundamentals.com/#example-1.2

Well it seems you already know the best way to do this.


Here is an example code of simple dynamic loader which loads several scripts in serial manner:

https://github.com/miohtama/Krusovice/blob/master/src/krootstrap.js

  • First detect the base URL of the current script file (loader) if you are using relative URLs. This needs some magic, because Javascript does not know its own location. If you have full HTTP URL to the file then you can skrip this test

  • Inject new tag to using DOM manipulation

  • Follow the script loading process and call a callback function when done (note that you cannot call any functions inside JS until it is loaded, thus you need to wait this callback)


The simplest you can do is something like this:

function importScript(path) {
    var el = document.createElement('script');
    el.type = 'text/javascript';
    el.src = path;
    var parent = document.getElementsByTagName('head')[0];
    if(!parent) parent = document.body;
    parent.appendChild(el);
}

Actually, it could be simpler still if you're sure the head always exists, of if you decide to always attach the script to the document body anyway.


There are many ways to load scripts dynamically, but what I think you want is something as simple as this:

function importScript(path) {
  document.write('<script type="text/javascript" src="' + path + '"></scr' + 'ipt>');
}

importScript('/scripts/jquery-1.6.2.min.js');
0

精彩评论

暂无评论...
验证码 换一张
取 消