Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading js files dynamically via another js file?

is there anyway to load other JS files from within a single JS file. I would like to point my individual pages "ITS" js file and that js file would load jquery, other js files.

I know i can just pop all these into the html i.e.

I was thinking of separations of concerns so i was wondering if anything exists already without me reinventing the wheel....

That i would just need to edit home.js to change what other js (jquery etc) are loaded for home.htm ... home.htm would just point to home.js

Thanks

like image 492
mark smith Avatar asked Oct 24 '09 15:10

mark smith


People also ask

Can I import a js file into another js file?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.

How do you load js file using js?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How do I load a JavaScript file asynchronously?

How to load a JavaScript file asynchronously from the server and automatically execute it. The HTML5 attribute async tells the browser to load this script without blocking the page. defer does essentially the same, but works on several older browsers, too.


2 Answers

You can take a look at dynamic script loading. Here's an excerpt from the article:

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'helper.js';
head.appendChild(script);
like image 103
Darin Dimitrov Avatar answered Sep 22 '22 13:09

Darin Dimitrov


For external domain JS link

var loadJs = function(jsPath) { 
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', jsPath);
    document.getElementsByTagName('head')[0].appendChild(s);
};
loadJs('http://other.com/other.js'); 

For same domain JS link (Using jQuery)

var getScript = function(jsPath, callback) {
    $.ajax({
        dataType:'script',
        async:false,
        cache:true,
        url:jsPath,
        success:function(response) {
            if (callback && typeof callback == 'function') callback();
        }
    });
};
getScript('js/other.js', function() { functionFromOther(); }); 
like image 33
molokoloco Avatar answered Sep 21 '22 13:09

molokoloco