jquery 实现插入页面
我们遇到了这个耗时的问题,并认为我们会与遇到相同情况的人分享这一问题。 很抱歉,这篇文章的长度,但是修复起来真是个难题!
问题:使用JavaScript / jQuery加载页面时,将脚本动态地插入DOM head标签。 这个示例说明了我们如何尝试在页面上加载openX脚本。
我们遇到以下问题:
- IE8由于加密的页面/网站而导致错误消息–要解决此问题,我们可以检查加密的页面,并且仅对未加密的页面加载OpenX脚本。
- 加载引用由第一个脚本创建的变量的第二个脚本,该变量导致未定义的错误消息–为解决此问题,我们仅添加了if语句以在使用变量之前检查该变量是否存在。
- document.write导致页面刷新–要修复此问题,请在页面加载后不要使用document.write。
(function() { if (window.location.protocol !== 'https') { var openx = document.createElement('script'); openx.type = 'text/javascript'; openx.async = true; openx.src = '
'; //Insert into head var theHead = document.getElementsByTagName('head')[0]; theHead.appendChild(openx); console.log('script inserted into head'); } })();
而且,如果您希望在头中包含多行js脚本(即,不仅是.js文件),您可以采用这种方式。
(function() { if (window.location.protocol !== 'https:') { /*Create dynamic scripts*/ var openX = document.createElement('script'); openX.type = 'text/javascript'; openX.defer = 'defer'; /*defer is only supported by IE*/ openX.async = true; /*async is a html5 proposal*/ openX.src = '
'; var multiOpenX = document.createElement('script'); multiOpenX.type = 'text/javascript'; multiOpenX.defer = 'defer'; multiOpenX.async = true; multiOpenX.innerHTML = ['var OX_4ddf11d681ca9 = OX();', 'OX_4ddf11d681ca9.addPage("2400");', 'OX_4ddf11d681ca9.fetchAds();' ].join('n'); /*Insert into head tag*/ var theHead = document.getElementsByTagName('head')[0]; theHead.appendChild(openX); theHead.appendChild(multiOpenX); } })();
在标题部分中使用innerHTML标记时,IE8似乎会产生错误。 除了不使用innerHTML的替代方法之外,我看不到任何解决方案。 我们可以还原为jQuery.getScript(),然后在第一个脚本参数加载后传入第二个脚本参数,如下所示:
$.getScript('ajax/test.js', function() {
alert('Load was performed.');
});
甚至将其放入函数中,然后从主体中调用它,如下所示:
您也可以用这种方式编写多行脚本(警告:有些浏览器会连续插入换行符,有些则不会)。
var multiOpenX =
'
最终剧本
在所有浏览器(包括IE8)中都可以使用的最终脚本:
另外,请检查此处以引用URL中的其他检查: http ://www.jquery4u.com/javascript/javascript-location-hostnames-url-examples/
翻译自: https://www.sitepoint.com/inserting-script-secure-encrypted-pages/
jquery 实现插入页面