Load javascript file every time a new page is loaded - javascript

I'm using http://instantclick.io on my website (a pjax jquery plugin) and I'm experiencing some problems regarding javascripts. It's very temperamental - sometimes a page will load with all the scripting working fine, but other times parts of the scripts will not run. Also, scripts are running more than once. For example, if I set a console log in a .click() function, I'll see the console log multiple times when there should only be one.
In the instantclick.io documentation, it explains how to load a script on each page load:
If you have a snippet of JavaScript that you need to execute on every page change, use the following:
InstantClick.on('change', yourCallback);
But I need to run a whole js file rather than just a function. I have tried wrapping InstantClick.on('change', function(){ around my whole js file, but the scripts are still not running again after a new page is opened.
In my console, I'm seeing lots of errors relating to functions being undefined, which would indicate that the files are not being loaded each time.
How would I solve this? Thanks!

Write in callback code like this for adding js file dynamically to DOM
var jsFile=document.createElement('script');
jsFile.setAttribute("type","text/javascript");
jsFile.setAttribute("src", link);
document.getElementsByTagName("head")[0].appendChild(jsFile);
And change link to url path to your js file.

use it like this
long dateTimeSec = new Date().getTime();
<link rel="stylesheet" href="bootstrap/css/bootstrap.css?v=<%=dateTimeSec%>">

Related

catch every script load-complete event with javascript or jQuery

I need to know when a script is loaded and it's code is executed so that I can make sure the variables are not undefined. I searched and did not find any question like this one... again I need loaded-executed event not just download-complete.
and I will use 'id' on each script so I can find which is loaded.
<script src="utils.js" id="js_utils"></script>
If you're not loading scripts dynamically, you can rely on their order of running (which would be the order in which they appear in the document), see here:
load and execute order of scripts
Otherwise, you can either:
Add a line of code to the end of each script file loaded dynamically that runs your block of code.
or
If you don't have the ability to edit those files, start an interval as soon as you inject them into the code, tracking the object you want set before running your block of code.

Deferring dynamically added Javascript

I need to load some Javascript dynamically after the page has loaded.
Something like this:
page loads
page adds script element with src = "file1.js"
page adds script element with src = "file2.js"
file2.js has a dependency on file1.js - it adds properties to an object defined in file1.js
The problem is that file2.js is loading first (because it is smaller), and is immediately throwing an error because its dependency doesn't exist.
Is there a way for me to defer evaluation/execution of these new scripts until they have all loaded. (There is actually more than two scripts)
If I were to just embed these scripts in a page normally in authored HTML, then it seems that the browser loads all scripts, then evaluates them. But it is behaving differently because I'm adding script elements on the fly.
Thanks
There's a library called RequireJS that handles exactly this situation, and handles every situation you never realized were problems - http://requirejs.org/docs/start.html
Can't you wrap the contents of the files in functions and call them after everything has loaded?
Two suggestions for you:
Have a look at http://requirejs.org/ It solves this problem, among
others.
Or, roll your own simple js loader function. It would be a function that
uses ajax to load a script and then calls a callback when it's done.
Call this loader function in a nested way so that you load your
scripts in the right order.

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.

How to write javascript code using external files only

When using HTML5 Boilerplate, you are given a script.js file and the jquery file are all loaded after the body.
How do I know when to call certain code for a specific page? For eg. What if on /maps I want to load google maps dynamically, how do I accomplish this without putting it on the page and using script.js file while having it not load the map for all pages?
Basically, how do I structure my code when I can't have any script in my pages? How do I know what code to call for a particular page?
Script files that are included are immediately executed, so inside the script file you could have a section check the URL of the page you're on.
For example, something like this:
if (window.location.href === "http://myapp.com/maps") {
// call the map function or whatever ...
}
But, out of curiosity, why can't you add a script file to the specific page you're on? I'd only recommend the solution above if you absolutely cannot edit the HTML of your pages.
I too have the same question. I searched and just found these two
http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/
http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/
I am going through of this, and not yet completely reviewed. See if it is useful to you in between.

Is it possible to prevent/remove any cached script declared by dojo.require?

I'm encountering an issue where most of a page's main logic is offset in a JS file and initialized within a dojo.require call to simplify debugging and development. We're encountering a case where an offload to another page, and then back to the first one and nothing inside our require script loads. I understand this is due in part to how dojo.require re-uses cached pages, but I can't go back to the cached version either. Is there a way, besides pasting all the scripts inside the page itself, to force Dojo to reload any require regardless of if it has been cached or not?
Force it to be reloaded in HTML.
<script type="text/javascript" src="path/to/my/module/name.js"></script>
<script type="text/javascript">
...
dojo.require("my.module.name");
...
</script>
I don't know if there is any problem on doing it but it does work.
Is there a reason you can't do this the "right" way, by putting the relevant code inside a function and then just calling said function again whenever you want?
If you still think you need to mess with the module loader though I think there are two alternatives after a quick check on the dojo.require source code:
Try to manually clear the module cache
delete d._loadedModules['my.module.name'];
Directly call the internal loader:
var relpath = d._getModuleSymbols(moduleName).join("/") + '.js';
d._loadPath(relpath, null);
(Try these at your own risk)

Categories