How can I call a library script after page is loaded? - javascript

I'm trying to call a library script (locomotive) in vanilla JS without Jquery, after the whole page and its assets had loaded. I've already tried with something like this:
<body onload="script('./js/lib/locomotive.min.js')";>
But it isn't working, the whole page loads but the script is never called. I've also tried placing the defer after the scripts call, but still nothing. I saw this other solution in other comments:
document.addEventListener("DOMContentLoaded", function(){
//....
// **But I don't know how to call in here the
*./js/lib/locomotive.min.js***
});
Is there something else I could try?

Your answer may be how to dynamic import script in js.
the base way is that insert a tag by dom api.
e.g.
const script = document.createElement('script')
script.src = './js/lib/locomotive.min.js'
document.head.appendChild(script)
if you wanna more functions, plz try loadjs

Related

Delay function call when dynamically loading javascript files

I am using enquire to dynamically load javascript files but hitting what I can only assume to be a loading priority problem since it works some of the time. Is there a way to hold off running a function until all files are loaded?
The relevent bit of enquire is
enquire.register("screen and (min-width: 564px)", {
match : function() {
loadJS('script/jquery.js');
loadJS('script/jquery.slides.min.js');
loadJS('script/TMSScript.js');
}
and the load function is
function loadJS(url)
{
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.head.appendChild(script);
}
The function I need to run is located at the end of TMSScript.js and it calls the jquery plugin so all 3 files need to be loaded in order for it to work. If I load all files in the header then the function will execute fine with a simple onload call in the body.
The idea is that a different method will be used on mobiles for my gallery (probably jquery mobile) and I don't want to load any unnecessary files.
Someone may correct me, but I believe outside of either loading these three in separate script tags placed in the correct order, or loading a single js file with these plugins concatenated in the correct order, you can't. Loading a src on a programatically created element now runs in an async fashion (in current browsers anyways I beleive), meaning you wouldn't be sure exactly when it's going to return back, and in what order.
It sounds like you want to use something like browserify or require.js which can help handle what you're trying to accomplish. I suggest checking out those projects.

How do I use Firebase in an external Javascript file

This is probably a very simple issue, but I've been trying to use Firebase in an external javascript file that is being used with an HTML file and can't get it to work properly. I am planning to use this file for many other similar pages, so I'd rather keep it in an external document. Specifically, my code is:
$(function() {
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.src= 'https://cdn.firebase.com/v0/firebase.js';
head.appendChild(script);
var Database = new Firebase('https://myfirebase.firebaseIO.com/');
...
but when I try to run it, it says that the Firebase object/keyword is undefined. I know that the script is being correctly appended to the HTML page because I've checked the HTML on the page after running the code.
I have also read somewhere that you might need to have a personal server to run Firebase, but frankly I don't really know what that means - in any case, I use Mac OSX and run all of my HTML and Javascript in Chrome.
Thank you very much!
The problem is that using document.createElement does not force the script to be loaded and rendered before your inclusive script is invoked (it's being invoked now). There are no guarantees by this method on when the script you include will get invoked.
Additionally, you are loading the script onDomReady by putting it inside $(function() {...}); you would want to insert it into the header immediately, not wait for the entire document to load.
The simplest answer is to just put Firebase into the head of the html page; you haven't really explained your limitations here, but I assume this isn't an option for you. If it is, KISS.
Another simple answer is to utilize jQuery, since you obviously have it available.
$.getScript('https://cdn.firebase.com/v0/firebase.js', function() {
// now I can use Firebase
});
You can also accomplish this with other methods (wait until Firebase is defined using a setInterval; utilize other script retrieval methods besides document.createElement--try googling "load scripts dynamically via javascript load order"), but I think this covers your needs sufficiently.

Adding external scripts in DOM from javascript code

I have included 3 external js files at the end of body.
Suppose my document already contains a js named as insertlibs.js and here is the code
var script1 = document.createElement('script');
script1.src='http://code.jquery.com/jquery-latest.js';
script1.type='text/javascript';
document.getElementsByTagName('Body').item(0).appendChild(script1);
// Similar way to include underscore
var script2 = document.createElement('script');
script2.src='hhttp://documentcloud.github.com/backbone/backbone-min.js';
script2.type='text/javascript';
document.getElementsByTagName('Body').item(0).appendChild(script2);
But what is happening sometimes, it is throwing an error that $ is not defined and I tried to debug in Firefox and there is a parallel download occurring for jquery and backbone and sometimes backbone library getting download earlier than jQuery which is causing this error.
As far as i know that if a script tag is included, it will block further request So as soon as I add jquery in dom. I am confused about the workflow here happening.
So i have found the solution, I merged both the js and making a single call which is working perfectly but that does not explain me the flow happening in above case. Please help.
This is because you are attempting to include backbone without ensuring that jquery has been completely loaded. To correct this, you can use the script's onload attribute to attach a callback which will be fired when jquery is loaded.
For ex:
var script1 = document.createElement('script');
script1.src='http://code.jquery.com/jquery-latest.js';
script1.type='text/javascript';
// add an onload handler
script1.onload = function() {
// load the rest of the scripts here
var script2 = document.createElement('script');
script2.src='hhttp://documentcloud.github.com/backbone/backbone-min.js';
script2.type='text/javascript';
document.getElementsByTagName('Body').item(0).appendChild(script2);
}
document.getElementsByTagName('Body').item(0).appendChild(script1);
As far as i know that if a script tag is included, it will block further request
No, the blocking / synchronous download is only when the tags are right in the parsed HTML (or are inserted via document.write during the parse); dynamically DOM-appended scripts load asynchronously and in parallel.
To do that but ensure that scripts are executed when their dependencies are met, you need to use AMD loaders.

Inject external javascript file in html body after page load

I want to load an external javascript after page is loaded. Actually the javascript contains source for an ad and its making page load slow. All I want is to delay loading & execution of ads to make sure fast page load.
thanks,
Bilal
You may just use this script at the last tag of your body block:
<script type="text/javascript">
var script = document.createElement('script');
script.setAttribute('src', 'http://yourdomian.com/your_script.js');
script.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(script);
</script>
var script=document.createElement('script');
script.type='text/javascript';
script.src=url;
$("body").append(script);
Courtsey
$("#selector").click(function(){
$.getScript("YourScript.js");
});
Then Run what is implemented in that script
I would look at using asynchronous Javascript loading. There are frameworks for this such as requireJS.
Without using something like jQuery getScript() and a promise or a proper loading library like requireJS, the script can be included in the page, but will load async so there's no guarantee it will be ready when you need it. If you're already using jQuery, the simple answer is then:
$.getScript( scriptUrl ).then( function() {
//do this ONLY after the script is fully loaded
});

Load js files after ajax inclusion

This is the deal, i'm importing some php files, one of the files has a slider, this slider requires .js files.
But when i make the ajax call, the file is imported but the js files aren't. Is this supposed to be like this?
I tried this:
var script = document.createElement('script');
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
window.onload=function(){
$(".cs_article").append('<p>Tdkasdlasdlkamsdklasmdasdaest</p>');
$.getScript('js/jquery.ennui.contentslider.js');
$.getScript('js/jquery.easing.1.3.js');
};
Kinda works, well, the append works on the DOM even with it being already loaded, but i can't get the scripts to run...
I've done my homework, searched on google, and found several ways of importing the scripts, but all end up with the same result...
this works
https://github.com/chriso/load.js
Bind your window.onload function to yourjQueryScriptTag.onload instead; before setting the src and appending it to the DOM, since onload may fire before jQuery is loaded.
http://jsfiddle.net/5SbXc/
Also, you may want to consider upgrading to a newer version of jQuery if possible.

Categories