Reputation: 531
I have a multi-page site that requires quite a bit of off-site JS files. I wish to call all of these files in an external file on my site that is accessed by all the pages so I can easily make site-wide changes if necessary. I think it might be better to show you want I mean:
What I Have: HTML
<head>
<script async src="https://www.googletagmanager.com/gtag/js?id=xxxxxxxxxxxxxxx"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'xxxxxxxxxxxxxxxx');
</script>
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
window.OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
});
});
</script>
<script async src=https://cse.google.com/cse.js?cx=xxxxxxxxxxxxxxxx></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js></script>
<script src=res/cookie.js defer></script><script>window.addEventListener(load,function(){window.wpcc.init({colors:{popup:{background:#222222,text:#ffffff,border:#b5e1a0},button:{background:#b5e1a0,text:#000000}},position:bottom-right,corners:small,padding:small,margin:large,transparency:5,content:{href:legal/cookie-policy,message:By using our site, you agree to our use of cookies. We use cookies to ensure that you have the best experience on our site!,link:View our Cookie Policy for Details,button:Understand!}})});</script>
</head>
For some reason the quotation mark (") is not showing in the code above, note that there are quotation marks, and the code does work.
What I Want:
HTML
<head>
<script src="/js/load.js"></script>
</head>
load.js
Some sort of code here that can call all of the scripts.
If there is a better way to do this (Like have an 0px by 0px iframe with the code) that would work will Google Analytics and other trackers, please let me know!
Upvotes: 2
Views: 92
Reputation: 531
You can use the jQuery "Get Script" command, like this:
In the HTML file:
//Calls jQuery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
//Calls external js file
<script src="/header.js"></script>
header.js:
//Example 1:
$.getScript( "https://cdn.onesignal.com/sdks/OneSignalSDK.js" )
window.OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "c4419c4b-c4d5-4238-ba9c-d19a533845f0",
});
});
//Example 2:
$.getScript( "https://cse.google.com/cse.js?cx=xxxxxxxxxxxxxxxx" )
Upvotes: 1